warshall-floyd算法:POJ No 2139 Six Degress of Cowvin Bacon(任意两点最短路径))

题目: http://poj.org/problem?id=2139

题解:N只牛,在一组的两只牛,分别两只之间为 “1度”,自己到自己为0度,M组牛。求,N只牛之中,两只牛之间 平均最短度数*100。模板Floyd算法,求任意两点之间最短路径。

#include 
#include 
#include 
using namespace std;

const int maxn = 300 + 24;
const int INF = 99999999;
int N, M;           // N个牛 ,M组电影 
//不存在的时候等于无穷大 或者
//d[i][i] = 0 
int d[maxn][maxn];  //d[u][v]表示边e=(u,v)的权值
int x[maxn];

void warshall_floyd();
void init();

void init()
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (i == j) {
                d[i][j] = 0;
            } else {
                d[i][j] = INF;
            }
        }
    }
}

void warshall_floyd()
{
    //经过顶点和不经过顶点的情况 
    for (int k = 0; k < N; k++) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
            }
        }
    }
}

void solve()
{
    int n;
    scanf("%d%d", &N, &M);
    init();
    
    while (M--)
    {
        scanf("%d", &n);
        for (int i = 0; i < n; i++) {
            scanf("%d", &x[i]);
            --x[i];
        }
        
        for (int i = 0; i < n; i++) 
        {
            for (int j = i + 1; j < n; j++) {
                d[x[i]][x[j]] = d[x[j]][x[i]] = 1;
            }
        }
    }
    warshall_floyd();
    int ans = INF;
    for (int i = 0; i < N; i++) 
    {
        int sum = 0;
        for (int j = 0; j < N; j++) {
            sum += d[i][j];
        }    
        ans = min(ans, sum);
    }
    
    printf("%d\n", 100 * ans / (N - 1));
    
}

int main()
{
    solve();
    
    return 0;
    
}

 

转载于:https://www.cnblogs.com/douzujun/p/6869635.html

你可能感兴趣的:(warshall-floyd算法:POJ No 2139 Six Degress of Cowvin Bacon(任意两点最短路径)))