poj 3463(最短路和比最短路大1的路的数量)(dijkstra)
求最短路和比最短路大1的路的数量
dij松弛的条件改变下,有四种情况
1.比最短路短2.等于最短路3.长与最短路但短于次短路4.等于次短路
具体见代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 #include <vector> 7 using namespace std; 8 const int inf = 0x3f3f3f3f; 9 const int maxn = 1005; 10 int n,m,S,F; 11 struct edge 12 { 13 int v,c; 14 edge(){} 15 edge(int v, int c):v(v), c(c){} 16 }; 17 vector <edge> adj[maxn]; 18 19 void init() 20 { 21 int u,v,c; 22 scanf("%d%d", &n, &m); 23 memset(adj, 0, sizeof(adj)); 24 for (int i = 0; i < m; ++i) 25 { 26 scanf("%d%d%d", &u, &v, &c); 27 adj[u].push_back(edge(v,c)); 28 } 29 scanf("%d%d", &S, &F); 30 } 31 32 int dij(int src) 33 { 34 bool vis[maxn][2]; 35 int dis[maxn][2],cnt[maxn][2]; 36 int v,c; 37 for (int i = 0; i <= n; ++i) 38 { 39 vis[i][0] = vis[i][1] = 0; 40 dis[i][0] = dis[i][1] = inf; 41 cnt[i][0] = cnt[i][1] = 0; 42 } 43 dis[src][0] = 0;cnt[src][0] = 1; 44 /*for (int i = 0; i < adj[src].size(); ++i) 45 { 46 v = adj[src][i].v; 47 c = adj[src][i].c; 48 dis[v][0] = c; 49 cnt[v][0] = 1; 50 } 51 vis[src][0] = 1;*/ 52 for (int i = 1; i < n * 2; ++i) 53 { 54 int tmp = inf, k = src, kind=0; 55 for (int j = 1; j <= n; ++j) 56 { 57 if (!vis[j][0] && tmp > dis[j][0]) 58 { 59 tmp = dis[j][0]; 60 k = j; 61 kind = 0; 62 } 63 else if(!vis[j][1] && tmp > dis[j][1]) 64 { 65 tmp = dis[j][1]; 66 k = j; 67 kind = 1; 68 } 69 } 70 if(tmp == inf) break; 71 vis[k][kind] = 1; 72 for (int j = 0; j < adj[k].size(); ++j) 73 { 74 v = adj[k][j].v; 75 c = adj[k][j].c; 76 if (dis[v][0] > tmp + c) 77 { 78 dis[v][1] = dis[v][0]; 79 dis[v][0] = tmp +c; 80 cnt[v][1] = cnt[v][0]; 81 cnt[v][0] = cnt[k][kind]; 82 } 83 else if (tmp + c == dis[v][0]) 84 cnt[v][0] += cnt[k][kind]; 85 else if (dis[v][1] > c + tmp) 86 { 87 dis[v][1] = c + tmp; 88 cnt[v][1] = cnt[k][kind]; 89 } 90 else if (dis[v][1] == tmp + c) 91 cnt[v][1] += cnt[k][kind]; 92 } 93 } 94 if (dis[F][0] + 1 == dis[F][1]) 95 return cnt[F][0] + cnt[F][1]; 96 else 97 return cnt[F][0]; 98 } 99 int main() 100 { 101 int t; 102 scanf("%d", &t); 103 while (t--) 104 { 105 init(); 106 printf("%d\n",dij(S)); 107 } 108 return 0; 109 }