跳到正文

题解

UVA821题解

Istruggle约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年1月2日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
UVA821

版本

  1. v1当前

思路:

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

参考代码如下:

C++
#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;
} 
原文