PAT A1030 Travel Plan(30 分)

总结:

1.常规套路,关键想想怎么存储图,然后就easy了

代码:

#include<iostream>
#include<vector>
#include<map>
using namespace std;
int vi[600];
struct road{
    int st;
    int end;
    int cost;
    int dis;
};
vector<vector<road> > pp;
map<int, vector<vector<int>>>sg;
int n, m, s, d;
int best[1000][1000];
int minlen = 99999999, totalen = 0;
int mincost = 999999, totalcost = 0;

void dfs(int index,vector<int>sh)
{
    if (index == d)
    {
        if (minlen > totalen){ minlen = totalen; mincost = totalcost; sg[minlen].push_back(sh); }
        else if (minlen == totalen&&mincost > totalcost){ minlen = totalen; mincost = totalcost; sg[minlen].push_back(sh); }
        return;
    }
    vi[index] = 1;
    for (int i = 0; i < pp[index].size(); i++)
    {
        if (vi[pp[index][i].end] == 0)
        {
            totalen += pp[index][i].dis;
            totalcost += pp[index][i].cost;
            sh.push_back(pp[index][i].end);
            dfs(pp[index][i].end,sh);
            totalen -= pp[index][i].dis;
            totalcost -= pp[index][i].cost;
            sh.pop_back(); vi[pp[index][i].end] = 0;
        }
    }
}
int main()
{
    cin >> n >> m >> s >> d;
    pp.resize(n);
    for(int i = 0; i < m; i++)
    {
        road s; road ps;
        scanf("%d%d%d%d",&s.st,&s.end,&s.dis,&s.cost);
        ps.st = s.end; ps.end = s.st; ps.dis = s.dis; ps.cost = s.cost;
        pp[s.st].push_back(s); pp[ps.st].push_back(ps);
    }
    vector<int> sh;
    sh.push_back(s);
    dfs(s,sh);
    for (int i = 0; i < sg[minlen][sg[minlen].size() - 1].size(); i++)
        printf("%d ", sg[minlen][sg[minlen].size() - 1][i]);
    cout << minlen << " " << mincost;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/82255092
今日推荐