POJ - 3660 Cow Contest (floyd,传递闭包)

题意:有N个奶牛, M个比较,a b标名a能够击败b,问最终能够确定排名的奶牛个数为多少个
思路:从排序的角度来讲我们肯定会先想到拓扑排序,但是拓扑排序只能知道是否排序唯一,不能够得到
确定排序的个数
所以换一个思路如果 一个点与其他所有点之间都有关系那么这个点就能够确定排名
这就涉及到传递闭包的操作,使用floyd算法

完整代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 105;
const int maxm = 1e4;
const int inf = 0x3f3f3f3f;
int g[maxn][maxn]; 
int n,m;
int floyd(){
    int cnt = 0;
    for(int i =1;i<=n;i++)
        for(int k = 1;k<=n;k++)
            for(int j=1;j<=n;j++){
                if(g[k][i]&&g[i][j]) g[k][j] = 1;//传递关系 
            }
    int tmp = 0;
    for(int i=1;i<=n;i++){
        for(int k=1;k<=n;k++){
            if(k==i) continue;
            if(g[i][k]||g[k][i]) tmp++;//确定是否有联系
        }
        if(tmp == n-1) cnt++;
        tmp = 0;
    }
    return cnt;
}
int main(){
    while(cin>>n>>m){
        memset(g,0,sizeof(g));
        for(int i=0;i<m;i++){
            int u ,v;
            cin>>u>>v;
            g[u][v] = 1;
        }
        cout<<floyd()<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/Tianwell/p/11288856.html