1. 程式人生 > >POJ3275:Ranking the Cows(Bitset加速floyd求閉包傳遞)

POJ3275:Ranking the Cows(Bitset加速floyd求閉包傳遞)

tel 還需 clu red 什麽 eve init osi rod

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 cowY.

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?"

題意:有N頭奶牛,現在給出M對產奶量關系U>V,問至少還需要知道多少奶牛可以做到全部奶牛產奶關系。

思路:有向圖,問至少再加多少邊,使得任意兩點S、T的可以到達(S到達T或者到達S)。閉包傳遞後不能到達的需要加邊,ans++。

至於為什麽閉包傳遞後不連通就就要ans++呢,假設已知了1>2>3>4,5>6>7,我們知道了4>5不就行了嗎,ans=1啊。

但是註意題目說的是"確定",而比較了4和5之後可能會4<5,即任然不可以把知道全部順序。

所以剩下對於C(n,2)對關系裏不確定的關系,都有知道才能“確定”所有的大小關系。

#include<cstdio>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1010;
bitset<maxn>mp[maxn];
int main()
{
    int N,M,ans,i,j,k;
    while(~scanf("%d%d",&N,&M)){
        ans=0;memset(mp,0,sizeof(mp));
        for(i=1;i<=M;i++){
            scanf("%d%d",&j,&k);
            mp[j].set(k);
        }
        
        for(k=1;k<=N;k++)
         for(i=1;i<=N;i++)
          if(mp[i][k])
           mp[i]|=mp[k];
        for(i=1;i<=N;i++)
         for(j=i+1;j<=N;j++)
          if(!mp[i][j]&&!mp[j][i])
           ans++;
        printf("%d\n",ans);
    }
    return 0;
}

POJ3275:Ranking the Cows(Bitset加速floyd求閉包傳遞)