N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M(1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..M+1: Each line contains two space-separated integers that describe the competitors and results (the first integer, A, is the winner) of a single round of competition: A and B
Output
* Line 1: A single integer representing the number of cows whose ranks can be determined
Sample Input
5 5
4 3
4 2
3 2
1 2
2 5
Sample Output
2
題意:
一場比賽的數據丟了,這個人給你比賽數據(有向圖)讓你計算有多少個cow的排名是可以準確得出的。輸出準確得出cow的數量。
思路:
- 首先,反向建圖,邊權值默認初始爲1(有連接的,無連接的初始爲INF)。如圖。
那麼這樣就行了嗎?肯定不行,如果這樣去跑一遍Floyd的話,是什麼作用沒有的。
這裏有一個重要的結論(肯定都知道的):
如果能確定這個點的排名,這個點必然和其他的所有點又有關係,並不一定是直接關係
那這樣是不是就知道怎麼做了,我們只需要跑一遍Floyd就知道那些點有關係了。NO!!!!
試想一下,這個點如果和另一個有關係,我們只能建立有向圖,那麼上圖2點永遠和5點是永遠不能有關係的。那麼我們不放5->2置位1,2->5置位-1不就好了嗎?。最後統計一下i這個點和哪些點有關係(就是兩點間的值不是0)就好了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<algorithm>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
#define F1(i,a,b) for(int i=(a);i<(b);i++)
#define F2(i,a,b) for(int i=(a);i<=(b);i++)
#define F3(i,a,b) for(int i=(a);i>=(b);i--)
#define F4(i,a,b) for(int i=(a);i>(b);i--)
#define sc(x) scanf("%d",&x)
#define scc(x,y) scanf("%d%d",&x,&y)
#define scll(x) scanf("%lld",&x)
#define mem(x,a) memset(x,a,sizeof x)
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
typedef pair<int ,int> PII;
const int maxn = 1005;
int in[maxn];
int out[maxn];
int mp[maxn][maxn];
int N,M;
void Froyd(){
}
int main(){
while(scc(N,M)!=EOF){
mem(mp,INF);
for(int i=1;i<=N;i++) mp[i][i]=0;
for(int i=0;i<M;i++){
int v,u;
scc(v,u);
mp[u][v]=1;
mp[v][u]=-1;
}
Froyd();
int res=0,cnt=0;
for(int k=1;k<=N;k++){
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
if((mp[i][k]==1 && mp[k][j]==1)){ // 模改一下Floyd,關係的傳遞性
mp[i][j]=1;
mp[j][i]=-1; // 別忘了反向的關係
}
}
}
}
for(int i=1;i<=N;i++){
cnt=0;
for(int j=1;j<=N;j++){
// cout<<mp[i][j]<<" ";//可以吧這個和後面的cout<<endl;註釋取消觀察矩陣
if(mp[i][j]!=INF && mp[i][j]!=0){
cnt++;
}
}
//cout<<endl;
if(cnt==N-1) res++;
}
printf("%d\n",res);
}
return 0;
}