ranking the cows(floyd +bitset)

P2881 [USACO07MAR] Ranking the Cows G

题目描述

Each of Farmer John's N cows (1 ≤ N ≤ 1,000) produces milk at a different positive rate, and FJ would like to order his cows according to these rates from the fastest milk producer to the slowest.

FJ has already compared the milk output rate for M (1 ≤ M ≤ 10,000) pairs of cows. He wants to make a list of C additional pairs of cows such that, if he now compares those C pairs, he will definitely be able to deduce the correct ordering of all N cows. Please help him determine the minimum value of C for which such a list is possible.

FJ想按照奶牛产奶的能力给她们排序。现在已知有N头奶牛(1 ≤ N ≤ 1,000)。FJ通过比较,已经知道了M(1 ≤ M ≤ 10,000)对相对关系。每一对关系表示为“X Y”,意指X的产奶能力强于Y。现在FJ想要知道,他至少还要调查多少对关系才能完成整个排序。

输入格式

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

Lines 2..M+1: Two space-separated integers, respectively: X and Y. Both X and Y are in the range 1...N and describe a comparison where cow X was ranked higher than cow Y.

输出格式

Line 1: A single integer that is the minimum value of C.

输入输出样例 #1

输入 #1

5 5
2 1
1 5
2 3
1 4
3 4

输出 #1

3

说明/提示

From the information in the 5 test results, Farmer John knows that since cow 2 > cow 1 > cow 5 and cow 2 > cow 3 > cow 4, cow 2 has the highest rank. However, he needs to know whether cow 1 > cow 3 to determine the cow with the second highest rank. Also, he will need one more question to determine the ordering between cow 4 and cow 5. After that, he will need to know if cow 5 > cow 3 if cow 1 has higher rank than cow 3. He will have to ask three questions in order to be sure he has the rankings: "Is cow 1 > cow 3? Is cow 4 > cow 5? Is cow 5 > cow 3?"
首先这道题肯定要用到floyd,但是数据太大肯定要超时,这时候就要用到bitset,使用bitset要用到#include,如果说i可以到达k,k可以到达的点i都可以到达,每个a[i]后面都跟着一串01串,0代表不可以到达,1表示可以到到,a[i]|=a[k]表示将a[i]和a[k]后面的01川进行位运算,|运算符如果两个都是0时才为零,
回到这道题,对于头奶牛,一共有n-1+n-2+n-3+...+1条关系,如果a[i][j]=1说明i和j两头奶牛的关系已经确定了,然后用一共的关系减去已经确定的关系就是答案;

#include<iostream>
#include<bitset>
#include<algorithm>
using namespace std;
bitset<1005>a[1005];
int ans=0;
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)a[i][i]=1;
    for(int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        a[x][y]=1;
    }
    for(int k=1;k<=n;k++){
        for(int i=1;i<=n;i++){
            if(a[i][k])a[i]|=a[k];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
           if(a[i][j]==1&&i!=j)ans++;
        }
    }
    cout<<(n-1)*(n-1+1)/2-ans;
    
    

    return 0;
}
posted @ 2025-03-08 16:07  郭轩均  阅读(15)  评论(0)    收藏  举报