Ranking the Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 3510 Accepted: 1608
Description
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.
Input
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.
Output
Line 1: A single integer that is the minimum value of C.
Sample Input
5 5
2 1
1 5
2 3
1 4
3 4
Sample Output
3
Hint
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?”
Source
问题链接:POJ3275 Ranking the Cows
问题简述:给定N头奶牛(1 ≤ N ≤ 1,000)M(1 ≤ M ≤ 10,000)对关系。每一对关系<X,Y>表示X的产奶能力强于Y。需要调查多少对关系才能完成整个排序。
问题分析:关系闭包Floyd算法实现。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* POJ3275 Ranking the Cows */
#include <iostream>
#include <bitset>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000;
bitset<N + 1> g[N + 1];
int main()
{
int n, m, u, v;
while(~scanf("%d%d", &n, &m)) {
for(int i = 1; i <= n; i++)
g[i].reset();
for(int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
g[u][v] = 1;
}
// 位串实现关系闭包计算
for(int u = 1; u <= n; u++)
for(int v = 1; v <= n; v++)
if(g[v][u]) g[v] |= g[u];
int ans = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(g[i][j]) ans++;
printf("%d\n", n * (n - 1) / 2 - ans);
}
return 0;
}