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,只要一个点被搜索道两次,就证明有环
但在这个题目中自环是要排除的。eg:i->i这样
不算犯规
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
int a[110][110],q,n,ok;
int vis[110];
void dfs(int x){
for(int i=1;i<=n;i++){
if(a[x][i]&&vis[i]){
ok=1;return;
}
if(a[x][i]&&!vis[i]){
vis[i]=1;
dfs(i);
vis[i]=0;
if(ok)break;
}
}return;
}
int main()
{
while(cin>>n&&n>0)
{
int x,y;
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
scanf("%d%d",&x,&y);
if(x!=y)a[x][y]=1;
}
cin>>q;ok=0;vis[q]=1;
dfs(q);
ok?printf("No\n"):printf("Yes\n");
}
}
本文介绍了一个关于Benny设计的新C编译器的问题,重点在于如何判断源文件是否能够成功编译,特别是当链接阶段遇到循环引用时的情况。文章通过一个具体的示例,使用深度优先搜索算法(DFS)来解决这一问题。
720

被折叠的 条评论
为什么被折叠?



