求所有点直接的平均最短距离,保存一下出现过的点,题目保证是所有点连通,Floyd求出最短路以后两个for统计一下。
#include<bits/stdc++.h> using namespace std; const int maxn = 101; int g[maxn][maxn]; bool vis[maxn]; vector<int> p; const int INF = 0x3f3f3f3f; int main() { //freopen("in.txt","r",stdin); int u,v,kas = 0; memset(g,0x3f,sizeof(g)); for(int i = 1; i < maxn; i++) g[i][i] = 0; while(scanf("%d%d",&u,&v),u){ p.clear(); memset(vis,0,sizeof(vis)); g[u][v] = 1; vis[u] = vis[v] = true; while(scanf("%d%d",&u,&v),u){ g[u][v] = 1; vis[u] = vis[v] = true; } for(int i = 1; i < maxn; i++){ if(vis[i]) p.push_back(i); } int sz = p.size(); for(int k = 0; k < sz; k++){ int m = p[k]; for(int i = 0; i < sz; i++){ int u = p[i]; if(g[u][m]<INF){ for(int j = 0; j < sz; j++){ int v = p[j]; g[u][v] = min(g[u][v],g[u][m]+g[m][v]); } } } } int sum = 0; for(int i = 0; i < sz; i++){ int u = p[i]; for(int j = 0; j < sz; j++) if(i!=j){ int v = p[j]; sum += g[u][v]; g[u][v] = INF; } } printf("Case %d: average length between pages = %.3lf clicks ",++kas,(double)sum/(sz*(sz-1))); } return 0; }