DFS 确定排名
Cow Contest
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15820 | Accepted: 8815 |
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
Sample Input
5 5 4 3 4 2 3 2 1 2 2 5
Sample Output
2
思路:
如果要知道一个点的排名是否确定,我们可以这样考虑,找到排名比他高的和比他低的(不一定要知道比它高多少名或者低多少名,只要能确定大小即可);
先把给的每个点连成一个有向图(我这里的方向是大的指向向的),之后我们判断每一个点向上和向下可以找到多少个点,如果总的找到了n-1个点,说明这个点的排名就是可以知道的,记录下来。再继续寻找下一个点;
这里是用DFS搜索的;
#include<vector>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
#define INF 0x3f3f3f
int n,m,mp[110][110],flag,vis[110];
struct point{
vector<int> into; //该点的入度
vector<int> out; //该点的出度
}pt[110];
void DFS_out(int k){
if(vis[k])return;
vis[k]=1;
for(int i=0;i<pt[k].out.size();i++){
if(vis[pt[k].out[i]])continue;
flag++;
DFS_out(pt[k].out[i]);
}
}
void DFS_into(int k){
if(vis[k])return;
vis[k]=1;
for(int i=0;i<pt[k].into.size();i++){
if(vis[pt[k].into[i]])continue;
flag++;
DFS_into(pt[k].into[i]);
}
}
int main(){
scanf("%d%d",&n,&m);
int a,b;
for(int i=1;i<=m;i++){
scanf("%d%d",&a,&b);
pt[a].out.push_back(b);
pt[b].into.push_back(a);
}
int ans=0;
for(int i=1;i<=n;i++){
flag=0;
memset(vis,0,sizeof(vis)); //记得要初始化!!!
DFS_out(i);
memset(vis,0,sizeof(vis));
DFS_into(i);
if(flag==n-1)ans++;
}
printf("%d\n",ans);
return 0;
}