9 11
代码贡献者:http://my.csdn.net/cstur4
#include <iostream> #include <string> #include <algorithm> #include <memory.h> #include <cstdio> #include <cstdlib> #include <queue> #include <vector> using namespace std; #define MAX 0Xfffffff struct Node{ int p, d; int th; bool operator>(const Node&node)const{ if(d==node.d) return p>node.p; return d>node.d; } }; bool visit[1001]; int mapd[1001][1001]; int mapp[1001][1001]; int dis[1001]; int ps[1001]; priority_queue<Node, vector<Node>, greater<Node>> q; //应该使用小顶堆 int main(){ //freopen("in.txt", "r", stdin); int n, m; int a, b, d, p; while(cin>>n>>m, n+m){ for(int i=1;i<=n;++i){ visit[i] = false; dis[i] = MAX; ps[i] = MAX; for(int j=1;j<=n;++j){ if(i==j){ mapd[i][j] = mapp[i][j] = 0; continue; } mapd[i][j] = MAX; mapp[i][j] = MAX; } } for(int i=0;i<m;++i){ scanf("%d%d%d%d", &a, &b, &d, &p); if(d<mapd[a][b]){ mapd[a][b] = mapd[b][a] = d; mapp[a][b] = mapp[b][a] = p; } if(d==mapd[a][b]&&p<mapp[a][b]){ mapp[a][b] = mapp[b][a] = p; } } int s, t; cin>>s>>t; Node node; node.th = s; node.d = 0; node.p = 0; q.push(node); while(!q.empty()){ //BFS, kijstra算法求最小距离,其中有dp的思想 Node node = q.top(); q.pop(); if(visit[node.th]) continue; visit[node.th] = true; for(int i=1;i<=n;++i){ if(i!=node.th && mapd[node.th][i]!=MAX && visit[i]==false){ if(node.d + mapd[node.th][i] < dis[i]){ dis[i] = node.d + mapd[node.th][i]; ps[i] = node.p + mapp[node.th][i]; Node tmp; tmp.th = i; tmp.d = dis[i]; tmp.p = ps[i]; q.push(tmp); }else if(node.d + mapd[node.th][i] == dis[i] && node.p + mapp[node.th][i] < ps[i]){ ps[i] = node.p + mapp[node.th][i]; Node tmp; tmp.d = dis[i]; tmp.p = ps[i]; tmp.th = i; q.push(tmp); } } } } if( s==t ) printf("%d %d\n", 0, 0); else printf("%d %d\n", dis[t], ps[t]); } //fclose(stdin); }