3 2 1 2 5 6 2 3 4 5 1 3 0 0
9 11
第一次做最短路的问题还要考虑花费,有点痛苦啊,不过还是AC了。
要注意一下,这道题要考虑重复路径的问题(虽然题目没说),但是不考虑就得WA。
代码如下:
#include <cstdio> #include <algorithm> #include <cstring> #define MAX 1000000 using namespace std; int n,m; int st,en; struct node { int dis,cost; }dp[1111]; struct node2 { int dis,cost; }s[1111][1111]; int used[1111]; void init() { for (int i = 1;i <= n;i++) { dp[i].dis = MAX; dp[i].cost = MAX; used[i] = 0; } for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) { s[i][j].dis = MAX; s[i][j].cost = MAX; } } } int min(int a,int b) { if (a<b) return a; return b; } void dijkstra() { dp[st].dis = 0; dp[st].cost = 0; while (1) { int v = -1; for (int i = 1;i <= n;i++) { if (used[i]==0 && (dp[i].dis<dp[v].dis || v == -1)) v = i; } if (v == -1) break; used[v] = 1; for (int i = 1;i <= n;i++) { if (dp[i].dis == dp[v].dis+s[v][i].dis) { dp[i].cost = min(dp[i].cost,dp[v].cost+s[i][v].cost); } else if (dp[i].dis > dp[v].dis+s[v][i].dis) { dp[i].dis = dp[v].dis+s[i][v].dis; dp[i].cost = dp[v].cost+s[i][v].cost; } } } } int main() { while (~scanf ("%d %d",&n,&m) && (n||m)) { init(); while (m--) { int t1,t2,t3,t4; scanf ("%d %d %d %d",&t1,&t2,&t3,&t4); if ((s[t1][t2].dis == t3 && s[t1][t2].cost > t4) || s[t1][t2].dis > t3) //考虑重复路径 { s[t1][t2].dis = t3; s[t1][t2].cost = t4; s[t2][t1].dis = t3; s[t2][t1].cost = t4; } } scanf ("%d %d",&st,&en); dijkstra(); printf ("%d %d\n",dp[en].dis,dp[en].cost); } return 0; }