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
5 5
2 1
1 5
2 3
1 4
3 4
Sample Output
3
Hint
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=1000+100;
const int maxm=1000000+1000;
int n,m,ans;
int nc[2],head[2][maxn];//head[0]表示a大于b,head[1]表示小于
bool vis[maxn][maxn];
struct jjj{int to,nxt;}line[2][maxm];
inline void add(int a,int b,int c)
{
line[c][++nc[c]].to=b;
line[c][nc[c]].nxt=head[c][a];
head[c][a]=nc[c];
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(vis[a][b])continue;
vis[a][b]=1;
add(a,b,0);
add(b,a,1);
ans++;
}
for(int k=1,x,y;k<=n;k++)
{
for(int i=head[1][k];i!=-1;i=line[1][i].nxt)
{
x=line[1][i].to;
for(int j=head[0][k];j!=-1;j=line[0][j].nxt)
{
y=line[0][j].to;
if(vis[x][y]) continue;
vis[x][y]=1;
ans++;
add(x,y,0);
add(y,x,1);
}
}
}
printf("%d",n*(n-1)/2-ans);
return 0;
}
(2)bitset+传递闭包
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<bitset>
using namespace std;
int n,m,ans;
bitset<1005>a[1005];
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int c,b;
scanf("%d%d",&c,&b);
a[c][b]=1;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(a[j][i]) a[j]|=a[i]; //j和i的顺序不能变,不然会WA的很惨!!!
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(a[i][j]) ans++;
printf("%d",(n-1)*n/2-ans);
return 0;
}
这里要注意 if(a[j][i]) a[j]|=a[i]; i和j的顺序不能变
如果反了:
for ( int i = 1 ; i < = n ; i + + )
for ( int j = 1 ; j < = n ; j + + )
if ( a [ i ] [ j ] ) a [ i ] | = a [ j ] ;(错解)
a [ i ] 中第 j 位为 1 表示第i头牛比j高,每一次的按位或 ( | ) 会把a[ j ]中的1全部按位给到a[ i ],即传递给a[ i ]
我们会发现,当i为外循环时,a[ 1 ]只会被a[ j ] 维护一个循环,而此时的a[2]~a[n]还没有被维护,也就是说a[ 2 ]~a[ n ]中储存的数据不完整,即并不是全部比a[ j ]少的牛都储存到了a[ j ]中,之后同理,a[2]~a[n-1]都会有这个问题
所以算出的ans会比正确值小,C(n,2)-ans会比正确值大