1030 Travel Plan (30分) dij模板題
阿新 • • 發佈:2020-08-17
題目
https://pintia.cn/problem-sets/994805342720868352/problems/994805464397627392
題意
~~
Sample Input:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Sample Output:
0 2 3 3 40
code
#include <bits/stdc++.h> using namespace std; typedef long long ll; int N,M,S,D; struct node{ int d,c,num; }city[505]; struct edge{ int v,d,c; edge(int a,int b,int c1):v(a),d(b),c(c1){} }; vector<edge>G[505]; bool operator < (const node x,const node y) {return x.d>y.d;} bool visit[505]; int fa[505]; void dij() { for(int i=0;i<N;++i) { city[i].num=i; city[i].c=(i==S?0:INT_MAX); city[i].d=(i==S?0:INT_MAX); } priority_queue<node>Q; Q.push(city[S]); while(!Q.empty()) { node t=Q.top(); Q.pop(); if(visit[t.num]) continue; else visit[t.num]=1; int u=t.num; for(int i=0;i<G[u].size();++i) { int v=G[u][i].v; int dis=G[u][i].d; int cost=G[u][i].c; if(city[v].d>city[u].d+dis || (city[v].d==city[u].d+dis && city[v].c>city[u].c+cost)) { city[v].d=city[u].d+dis; city[v].c=city[u].c+cost; fa[v]=u; Q.push(city[v]); } } } } void path() { stack<int>st; int p=D; while(p!=S) { st.push(p); p=fa[p]; } cout<<S; while(!st.empty()){ cout<<" "<<st.top(); st.pop(); } } int main() { cin>>N>>M>>S>>D; for(int i=1;i<=M;++i) { int a,b,c,d; cin>>a>>b>>c>>d; G[a].push_back(edge(b,c,d)); G[b].push_back(edge(a,c,d)); } dij(); path(); cout<<" "<<city[D].d<<" "<<city[D].c<<endl; return 0;