poj3268 Dijkstra演算法 邊既有權又有花費
阿新 • • 發佈:2018-11-10
題意:
給你n個點,m條無向邊,每條邊都有長度d和花費p,給你起點s終點t,要求輸出起點到終點的最短距離及其花費,如果最短距離有多條路線,則輸出花費最少的。
程式碼:
#include<cstdio> #include<algorithm> #include<vector> #include<queue> #include<cstring> using namespace std; #define INF 1e9 const int maxn = 1000+10; int n,m; struct Edge { int from,to,dist,cost; Edge(int f,int t,int d,int c):from(f),to(t),dist(d),cost(c){} }; struct HeapNode { int d,c,u; HeapNode(int d,int c,int u):d(d),c(c),u(u){} bool operator<(const HeapNode&rhs)const { return d>rhs.d || (d==rhs.d && c>rhs.c); } }; struct Dijkstra { int n,m; vector<Edge> edges; vector<int> G[maxn]; bool done[maxn]; int d[maxn]; int c[maxn]; void init(int n) { this->n=n; for(int i=0;i<n;i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int dist,int cost) { edges.push_back(Edge(from,to,dist,cost)); m = edges.size(); G[from].push_back(m-1); } void dijkstra(int s) { priority_queue<HeapNode> Q; for(int i=0;i<n;i++) d[i]=INF,c[i]=INF; d[s]=c[s]=0; Q.push(HeapNode(d[s],c[s],s)); memset(done,0,sizeof(done)); while(!Q.empty()) { HeapNode x= Q.top(); Q.pop(); int u =x.u; if(done[u]) continue; done[u]= true; for(int i=0;i<G[u].size();i++) { Edge &e=edges[G[u][i]]; if(d[e.to] > d[u]+e.dist || (d[e.to]== d[u]+e.dist&&c[e.to]>c[u]+e.cost) ) { d[e.to]= d[u]+e.dist; c[e.to]= c[u]+e.cost; Q.push(HeapNode(d[e.to],c[e.to],e.to)); } } } } }DJ; int main() { while(scanf("%d%d",&n,&m)==2&&n) { DJ.init(n); for(int i=0;i<m;i++) { int u,v,d,c; scanf("%d%d%d%d",&u,&v,&d,&c); u--,v--; DJ.AddEdge(u,v,d,c); DJ.AddEdge(v,u,d,c); } int s,e; scanf("%d%d",&s,&e); s--,e--; DJ.dijkstra(s); printf("%d %d\n",DJ.d[e],DJ.c[e]); } return 0; }