思路:先求出每两点之间的最短路,建出n个最短路径图,然后枚举起点终点和中间点,计算条数用到拓扑图dp。。。
看别人的方法很巧妙地用floyd在计算最短路的时候就可以直接计算条数啦。。。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define pii pair<int, int> using namespace std; const int N = 100 + 7; const int M = 1e4 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 +7; int n, m, tot, d[N][N], head[N]; LL dp[N][N]; double ans[N]; bool in[N]; vector<int> Edge[N][N]; struct EDGE { int from, to, w, nx; } edge[M]; void add(int u, int v, int w) { edge[tot].from = u; edge[tot].to = v; edge[tot].w = w; edge[tot].nx = head[u]; head[u] = tot++; } void spfa(int s) { memset(in, false, sizeof(in)); queue<int> que; que.push(s); d[s][s] = 0, in[s] = true; while(!que.empty()) { int u = que.front(); que.pop(); in[u] = false; for(int i = head[u]; ~i; i = edge[i].nx) { int v = edge[i].to, w = edge[i].w; if(d[s][u] + w < d[s][v]) { d[s][v] = d[s][u] + w; if(!in[v]) in[v] = true, que.push(v); } } } for(int i = 0; i < tot; i++) { int u = edge[i].from, v = edge[i].to, w = edge[i].w; if(d[s][u] + w == d[s][v]) { Edge[s][v].push_back(u); } } } LL dfs(int s, int u) { if(s == u) return 1; if(dp[s][u] != -1) return dp[s][u]; dp[s][u] = 0; for(int k = 0; k < Edge[s][u].size(); k++) { int v = Edge[s][u][k]; dp[s][u] += dfs(s, v); } return dp[s][u]; } int main() { memset(head, -1, sizeof(head)); memset(d, inf, sizeof(d)); memset(dp, -1, sizeof(dp)); scanf("%d%d", &n, &m); for(int i = 1; i <= m; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); add(u, v, w); add(v, u, w); } for(int i = 1; i <= n; i++) { spfa(i); } for(int i = 1; i <= n; i++) { for(int j = i + 1; j <= n; j++) { LL cnt = dfs(i, j); for(int k = 1; k <= n; k++) { if(k == i || k == j) continue; if(d[i][k] + d[j][k] != d[i][j]) continue; LL ret = dfs(i, k) * dfs(j, k); ans[k] += 1.0 * ret / cnt; } } } for(int i = 1; i <= n; i++) { printf("%.3f ", ans[i] * 2); } return 0; } /* 3 3 2 */