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
题目大意:给出n个点,m条单向边(A等级高就能打败B),输出最终能确定等级的个数。
思路:刚开始看的时候一头雾水,需要明确找的到底是什么,是最能与其他点构成连通的中间点,然后想的是跑全图来松弛所有的点,最后找出与所有点相连的点。理论上讲这个思路和题意是吻合的,但是,,,没办法确定数量啊,因为最终形成的是一个网状关系图,无法判断端点是否为已确定的.......然后就接触到了传说中的传递闭包。
传递闭包的定义:通过矩阵乘法的特性进行传递,得到一个完全的可到达的关系图。(有点表述不清)
简单描述一下怎么利用矩阵乘法的。存图的时候单向边存1表示有路,用矩阵的每行乘以每列,即与矩阵的转置相乘,如何理解,转置后行变成了列,最终矩阵的(x1,y1)就表示原矩阵第x1行与转置矩阵第y1列相乘的结果,即为点x1连接的情况与点y1连接情况的传递,最终得出的矩阵就是传递完的图,但弗洛伊德是借用了这个结论,通过枚举中间点的情况来模拟传递的过程,而不是直接用矩阵解。同理,DFS传递闭包的实现利用了这个过程,通过不断的搜索相关点来模拟这个行列相乘的传递过程。
想了解一下DFS传递闭包:链接太长了,不美观
只能感叹,还好我大二了,刚学了矩阵.......(同时感谢昨晚半夜还热情为我讲解的大佬)
补上这个东西后这道题就十分明了了,这个传递闭包的实现方式可以选择弗洛伊德或者DFS,前者时间复杂度为(V^3),后者时间复杂度为(VE)。视情况选择喽。
代码如下:
#include<set>
#include<map>
#include<list>
#include<deque>
#include<cmath>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<stdio.h>
#include<sstream>
#include<stdlib.h>
#include<string.h>
//#include<ext/rope>
#include<iostream>
#include<algorithm>
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
#define per(i,a,b) for(int i=a;i<=b;++i)
#define LL long long
#define swap(a,b) {int t=a;a=b;b=t}
using namespace std;
//using namespace __gnu_cxx;
int p[105][105];
int main()
{
int n,m,a,b;
cin>>n>>m;
memset(p,0,sizeof(p));
while(m--)
{
cin>>a>>b;
p[a][b]=1;
}
per(k,1,n)
{
per(i,1,n)
{
per(j,1,n)
{
if(p[i][k]==1&&p[k][j]==1)//矩阵特性
{
p[i][j]=1;
}
}
}
}
int k=0,j;
per(i,1,n)
{
for(j=1;j<=n;j++)
{
if(i==j) continue;
if(p[i][j]==0&&p[j][i]==0)
{
break;
}
}
if(j>n) k++;
}
printf("%d",k);
return 0;
}