資料結構實驗之圖論七:驢友計劃【迪傑斯特拉演算法】(SDUT 3363)
阿新 • • 發佈:2018-12-11
分析:可以求簡單的任意兩點間最短距離的稍微變形,一個板子題。
#include <iostream> #include <bits/stdc++.h> using namespace std; int inf = 0x3fffff; int gra[1005][1005]; int mon[1005][1005]; int vis[1005]; int dist[1005]; int cost[1005]; void dijkstra(int s,int d,int n) { memset(vis,0,sizeof(vis)); for(int i = 0; i <= n; i ++) dist[i] = gra[s][i],cost[i] = mon[s][i]; int Min = inf, v, Micost = inf; for(int i = 1; i <= n; i ++) { Min = Micost = inf; for(int j = 1; j <= n; j ++) { if(!vis[j]){ if(dist[j] < Min){Min = dist[j]; v = j; Micost = cost[j]; } else if(dist[j] == Min) { if(cost[j] < Micost) { Min = dist[j]; v = j; Micost = cost[j]; } } } } vis[v] = 1; for(int j = 1; j <= n; j ++) { if(!vis[j]){ if(dist[j] > gra[v][j] + dist[v])dist[j] = gra[v][j] + dist[v],cost[j] = mon[v][j] + cost[v]; else if(dist[j] == gra[v][j] + dist[v]) { if(cost[j] > cost[v] + mon[v][j]){ dist[j] = gra[v][j] + dist[v],cost[j] = mon[v][j] + cost[v]; } } } } } printf("%d %d\n",dist[d], cost[d]); } int main() { int n,m,u,v,w,p,s,d,t; scanf("%d",&t); while(t--){ scanf("%d%d%d%d",&n,&m,&s,&d); for(int i = 0; i<= n; i ++) { for(int j = 0; j <= n; j ++) { if(i == j) gra[i][j] = 0,mon[i][j] = 0; else gra[i][j] = inf,mon[i][j] = inf; } } for(int i = 0; i < m; i ++) { scanf("%d%d%d%d",&u,&v,&w,&p); gra[u][v] = gra[v][u] = w; mon[u][v] = mon[v][u] = p; } dijkstra( s,d, n); } return 0; }