当前位置: 代码迷 >> 综合 >> POJ--2139--Six Degrees of Cowvin Bacon(转化为最短路径即可)
  详细解决方案

POJ--2139--Six Degrees of Cowvin Bacon(转化为最短路径即可)

热度:76   发布时间:2023-12-12 06:39:58.0

链接:http://poj.org/problem?id=2139

The cows have been making movies lately, so they are ready to play a variant of the famous game "Six Degrees of Kevin Bacon".

The game works like this: each cow is considered to be zero degrees of separation (degrees) away from herself. If two distinct cows have been in a movie together, each is considered to be one 'degree' away from the other. If a two cows have never worked together but have both worked with a third cow, they are considered to be two 'degrees' away from each other (counted as: one degree to the cow they've worked with and one more to the other cow). This scales to the general case.

The N (2 <= N <= 300) cows are interested in figuring out which cow has the smallest average degree of separation from all the other cows. excluding herself of course. The cows have made M (1 <= M <= 10000) movies and it is guaranteed that some relationship path exists between every pair of cows.

Input

* Line 1: Two space-separated integers: N and M

* Lines 2..M+1: Each input line contains a set of two or more space-separated integers that describes the cows appearing in a single movie. The first integer is the number of cows participating in the described movie, (e.g., Mi); the subsequent Mi integers tell which cows were.

Output

* Line 1: A single integer that is 100 times the shortest mean degree of separation of any of the cows.

Sample Input
4 2
3 1 2 3
2 3 4
Sample Output
100
Hint
[Cow 3 has worked with all the other cows and thus has degrees of separation: 1, 1, and 1 -- a mean of 1.00 .]

思路:构建cost[MAX][MAX]数组,依次找任意两点之间的最短距离。Floyd-Wrashall算法模板。

#include<algorithm> 
#include<cmath>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
//(Floyd-Wrashall算法)(求任意两点之间的最小距离)
const int MAX=310,INF=1e9+1; 
int cost[MAX][MAX];//cost[i][j]表示顶点i到顶点j的权值
int num[MAX];
int d[MAX];//顶点s出发的最短路径
bool used[MAX];//已经访问过的点
int V;//顶点数 
void floyd(){for(int k=1;k<=V;k++) {for (int i=1;i<=V;i++) {for (int j=1;j<=V; j++) {cost[i][j]=min(cost[i][j], cost[i][k] + cost[k][j]);}} } 
}
void init(){for(int i=0;i<MAX;i++)for(int j=0;j<MAX;j++){if(i==j)cost[i][j]=0;//到自身的距离是0 elsecost[i][j]=INF;}
}
int main(){init();int n,m;cin>>n>>m;int t;for(int i=0;i<m;i++){memset(num,0,sizeof(num));cin>>t;for(int i=0;i<t;i++) cin>>num[i];for(int j=0;j<t;j++)for(int k=j+1;k<t;k++){ cost[num[j]][num[k]]=1;cost[num[k]][num[j]]=1;} }V=n;floyd();//调用函数 int cnt=INF;//双重for循环的作用就是将从1,2,..,n个点出发到1,2,3,...,n的最短距离求出来,不用打表 for(int i=1;i<=n;i++){int sum=0; for(int j=1;j<=n;j++)sum+=cost[i][j];if(sum<cnt)cnt=sum;}cout<<100*cnt/(n-1)<<endl;
}