Solution:
传递闭包
//if a beats b and b beats c , then a beats c
//to cow i, if all the result of content(n-1) has been known,
//then the rank can be determined
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define maxn 1000 //if a beats b and b beats c , then a beats c int main()
{
long n,m,i,j,k,a,b,ans,total=;
bool vis[maxn][maxn];
scanf("%ld%ld",&n,&m);
for (i=;i<=n;i++)
for (j=;j<=n;j++)
vis[i][j]=false;
for (i=;i<=m;i++)
{
scanf("%ld%ld",&a,&b);
vis[a][b]=true;
}
for (i=;i<=n;i++)
for (j=;j<=n;j++)
for (k=;k<=n;k++)
vis[j][k]=vis[j][k] || (vis[j][i] && vis[i][k]);
//to cow i, if all the result of content(n-1) has been known,
//then the rank can be determined
for (i=;i<=n;i++)
{
ans=;
for (j=;j<=n;j++)
if (vis[i][j] || vis[j][i])
ans++;
if (ans==n-)
total++;
}
printf("%ld\n",total);
return ;
}
传递闭包标程+解释:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define maxn 1000 //n个点,点编号为1~n,m条边
//传递闭包:判断图中任意两点是否可达
//时间复杂度:n*n*n int main()
{
long n,m,i,j,k,a,b;
bool vis[maxn][maxn];
scanf("%ld%ld",&n,&m);
for (i=;i<=n;i++)
for (j=;j<=n;j++)
vis[i][j]=false;
for (i=;i<=m;i++)
{
scanf("%ld%ld",&a,&b);
vis[a][b]=true;
}
//如果是无向图,a能到达b意味着b也能到达a,所以可以求a->b(a<b),i<j<k
//如果没有if:操作n*n*n
//如果有if:判断n*n+n*(n-1)*n次,操作n*(n-1)*(n-2)
//所以直接不用if
//从j点到k点:从j到k经过的点的编号小于等于i(i=1,2,…,n)。当然也可以从j直达到k。
for (i=;i<=n;i++)
for (j=;j<=n;j++)
//if (i!=j)
for (k=;k<=n;k++)
//if (i!=j && i!=k)
vis[j][k]=vis[j][k] || (vis[j][i] && vis[i][k]);
//if (vis[j][i] && vis[i][k])
//vis[j][k]=true;
for (i=;i<=n;i++)
{
printf("%ld : ",i);
for (j=;j<=n;j++)
if (vis[i][j])
printf("%ld ",j);
printf("\n");
}
return ;
}
/*
5 5
1 2
2 3
1 3
4 5
5 3
*/
其实传递闭包跟floyd很像,原理都是一样的。