Ranking the Cows(POJ-3275 )
Problem 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
題意:已知有n頭牛,給出m對產量關系 x>y,求至少還要多少對產量關系才能給出所有牛的產量關系。
思路:n 頭牛一共有 n*(n-1)/2 對關系,現在給出 m 對關系,假設根據這 m 對關系無法確定的關系有?sum 對,則題目也就是求 (sum-n)/2
枚舉中間節點 K 之后就開始枚舉起點 x 和終點 y,若 x 與 k,或 y 與 k 之間不聯通,則無法確立關系,因此從起點 x 只檢查能通向 k 的節點,從終點 y 只檢查 k 能通向的節點,使用 Floyd 算法進行傳遞閉包運算,最后根據無法確定關系的牛的對數輸出結果即可。
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 1001 #define MOD 123 #define E 1e-6 using namespace std; int f[N][N]; int main () {int n,m;while(scanf("%d%d",&n,&m)!=EOF){for(int i=1;i<=m;i++){int x,y;scanf("%d%d",&x,&y);f[x][y]=1;}for(int k=1;k<=n;k++)for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if(f[i][k]&f[k][j])f[i][j]=1;for(int i=1;i<=n;i++)//一旦具自反性,輸出-1if(f[i][i]){printf("-1");return 0;}int sum=0;for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if(!f[i][j]&&!f[j][i])//一旦存在未知sum++;printf("%d",(sum-n)/2);}return 0; }?
總結
以上是生活随笔為你收集整理的Ranking the Cows(POJ-3275 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cow Picnic(POJ-3256)
- 下一篇: 放苹果(信息学奥赛一本通-T1206)