UVA821题解

· · 题解

思路:

  1. 每个网页可以看作有向图中的一个结点,因此可以在读数时使用邻接矩阵存图,并记录节点中最大的数 n,n 即为结点的个数。
  2. 用 Floyd 算出各个点之间的最短路。
  3. 累加各个节点之间的距离总和为 t 并记录路径数 num,但要判断起点和终点是否不同。
  4. 计算所有节点的平均距离为 \frac{t}{num},注意保留三位小数。

参考代码如下:

#include<iostream>
#include<cstring>
#include <cstdio>
using namespace std;
int way[105][105],n=-1,c=0;
int main()
{
    int a,b;
    while(true)
    {
        n=-1;
        memset(way,0x3f,sizeof(way));
        scanf("%d%d",&a,&b);
        if(a==0&&b==0)
        break;

        way[a][b]=1; 
        n=max(n,max(a,b));
        while(true)
        {
        scanf("%d%d",&a,&b);
        if(a==0&&b==0)
        break;

        n=max(n,max(a,b));
        way[a][b]=1;
        }
        for(int k = 1;k <= n;k++)
            for(int i = 1;i<=n;i++)
                for(int j = 1;j<=n;j++)
                way[i][j] = min(way[i][j],way[i][k]+way[k][j]);

        double num=0,t=0;
        for(int i =1;i<=n;i++)
        for(int j = 1;j<=n;j++)
        {
            if(i!=j&&way[i][j]<0x3f3f3f3f) 
            {
                t=t+way[i][j]; 
                num++;
            }
        }
        printf("Case %d: average length between pages = %.3lf clicks\n", ++c, t / num);
    }
    return 0;
}