These days Benny has designed a new compiler for C programming language. His compilation system provides a compiler driver that invokes the language preprocessor, compiler, assembler and linker. C source file (with .C suffix) is translated to relocatable object module first, and then all modules are linked together to generate an executable object file.
The translator (preprocessor, compiler and assembler) works perfectly and can generate well optimized assembler code from C source file. But the linker has a serious bug -- it cannot resolve global symbols when there are circular references. To be more specific, if file 1 references variables defined in file 2, file 2 references variables defined in file 3, ... file n-1 references variables defined in file n and file n references variables defined in file 1, then Benny's linker walks out because it doesn't know which file should be processed first.
Your job is to determine whether a source file can be compiled successfully by Benny's compiler.
Input
There are multiple test cases! In each test case, the first line contains one integer N, and then N lines follow. In each of these lines there are two integers Ai and Bi, meaning that file Ai references variables defined in file Bi (1 <= i <= N). The last line of the case contains one integer E, which is the file we want to compile.
A negative N denotes the end of input. Else you can assume 0 < N, Ai, Bi, E <= 100.
Output
There is just one line of output for each test case. If file E can be compiled successfully output "Yes", else output "No".
Sample Input
4
1 2
2 3
3 1
3 4
1
4
1 2
2 3
3 1
3 4
4
-1
Sample Output
No
Yes
我们看到这种一个连一个的就可以想到是DFS,但是应该链表也可以做。
我们首先根据他给的数据来构建一个有向图,从给出点用dfs进行图的遍历,
假如dfs下去遇到访问过的点,那么肯定在图中就存在环,且我们所求的点也在环中。
还有一点需要我们注意的是,就是同一个点相连(比如题中样例 3 3, 4,4)
下面上代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int vis[105];
int n;
int mp[105][105];
int flag=1;
void DFS(int x)
{
int i;
for(i=0;i<n;i++){
if(vis[i]==1&&mp[x][i]==1)
{
flag=0;
return ;
}
if(mp[x][i]==1)
{
vis[i]=1;
DFS(i);
vis[i]=0;
}
}
}
int main()
{
while(~scanf("%d",&n)){
if(n==-1) return 0;
int i,j,a,b;
memset(vis,0,sizeof(vis));
memset(mp,0,sizeof(mp));
for(i=0;i<n;i++){
scanf("%d%d",&a,&b);
if(a==b) continue;//注意这个,这个是不算的
mp[a][b]=1;
}
int cot;
scanf("%d",&cot);
flag=1;
DFS(cot);
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}
对了 还有一点,一定要记得清空地图和vis数组,我就是忘记清mp数组了,导致超时了。