1030 Travel Plan (30 分)

水~。

题意

有N个城市(编号为0~N-1)、M条道路(无向边),并给出M条道路的距离属性与花费属性。现在给定起点S与终点D,求从起点到终点的最短路径、最短距离及花费。注意:如果有多条最短路径,则选择花费最小的那条。

const int N=510;
struct Node
{
    int v,dis,cost;
};
vector<Node> g[N];
int dist[N];
bool vis[N];
int pre[N];
int f[N];
int n,m,st,ed;

void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    memset(pre,-1,sizeof pre);
    priority_queue<PII,vector<PII>,greater<PII>> heap;
    dist[st]=0;
    f[st]=0;
    heap.push({0,st});

    while(heap.size())
    {
        int t=heap.top().se;
        heap.pop();

        if(vis[t]) continue;
        vis[t]=true;

        for(int i=0;i<g[t].size();i++)
        {
            int j=g[t][i].v,w=g[t][i].dis,c=g[t][i].cost;
            if(dist[j] > dist[t] + w)
            {
                dist[j]=dist[t]+w;
                pre[j]=t;
                f[j]=f[t]+c;
                heap.push({dist[j],j});
            }
            else if(dist[j] == dist[t]+w && f[j] > f[t]+c)
            {
                f[j]=f[t]+c;
                pre[j]=t;
            }
        }
    }
}

void print(int x)
{
    if(x == -1) return;
    print(pre[x]);
    cout<<x<<' ';
}

int main()
{
    cin>>n>>m>>st>>ed;

    while(m--)
    {
        int a,b,dis,cost;
        cin>>a>>b>>dis>>cost;
        g[a].pb({b,dis,cost});
        g[b].pb({a,dis,cost});
    }

    dijkstra();

    print(ed);
    cout<<dist[ed]<<' '<<f[ed]<<endl;
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14462740.html