Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8846 | Accepted: 4977 |
Description
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
分析:
当且仅当一个点与其他点的关系都已确定时,他的等级才被确定。由此可以用Floyd算法找任意两点之间的最短路径,若dist[i][j]和dist[j][i]都为INF,那么i与j之间没有确定的关系。时间复杂度O(V^3)。
另外这类的传递闭包问题,还可以从点的入度考虑。应用优先队列把点按入度升序排列。若一次有多个点入度为零,那么这几个点的关系都不确定,将各点标为已访问并删去(同时删去它引出的边)。若只有一个点入度为零,且还未被访问,且小于它的点的数目等于n-当前图中点的数目,那么他的关系已被确定,标为已访问并删点。重复操作直到队列为空。若最终队列不为空(即队首元素入度不为零),说明原图中逻辑关系有矛盾(有环)。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
#define N 105
#define INF (1<<15)
#define min(x,y) (x<y?x:y)
int dist[N][N];
bool A[N][N];
int main(){
int n,m,u,v,ans;
while(scanf("%d%d",&n,&m)!=EOF){
memset(A,false,sizeof(A));ans=n;
for(int i=0;i<m;++i){
scanf("%d%d",&u,&v);
A[u][v]=true;
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(A[i][j]) dist[i][j]=1;
else dist[i][j]=INF;
}
dist[i][i]=0;
}
for(int k=1;k<=n;++k){
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
}
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(i!=j&&dist[i][j]==INF&&dist[j][i]==INF){
--ans;break;
}
}
}
printf("%d\n",ans);
}
return 0;
}