「POJ3275」Ranking the Cows
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
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
Sample Input
1 2 3 4 5 6 |
5 5 2 1 1 5 2 3 1 4 3 4 |
Sample Output
1 |
3 |
Hint
题解
网上似乎都是floyd传递闭包。。
很直观的搜索
如果a>b相当于a到b连一条有向边,ans++
搜索每一个点
如果a能到b,b也能到c,a到c连一条有向边,ans++
答案是C(n,2)-ans
本质和floyd似乎一样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include<cstdio> #include<cstring> #include<iostream> using namespace std; int n,m,ans,cnt,head[1001],q[1001]; bool mp[1001][1001]; struct data{int to,next;}e[500001]; void insert(int u,int v) {e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;} void bfs(int x) { int t=0,w=1,now,i; q[t]=x; while(t<w) { now=q[t];t++;i=head[now]; while(i) { if(!mp[x][e[i].to]) { mp[x][e[i].to]=1; ans++; q[w++]=e[i].to; if(now!=x)insert(x,e[i].to); } i=e[i].next; } } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); insert(u,v); } for(int i=1;i<=n;i++)bfs(i); printf("%d",n*(n-1)/2-ans); return 0; } |