判断给定图是否存在合法拓扑序列
Problem Description
给定一个有向图,判断该有向图是否存在一个合法的拓扑序列。
Input
输入包含多组,每组格式如下。
第一行包含两个整数n,m,分别代表该有向图的顶点数和边数。(n<=10)
后面m行每行两个整数a b,表示从a到b有一条有向边。
Output
若给定有向图存在合法拓扑序列,则输出YES;否则输出NO。
Example Input
1 0 2 2 1 2 2 1
Example Output
YES NO
代码如下:
#include <iostream>
#include<string.h>
using namespace std;
const int inf=30;
int c[inf],G[inf][inf];
int topo[inf];
int n,m,i;
bool dfs(int u)
{
c[u]=-1;
for(int v=1; v<=n; v++)
if(G[u][v])
if(c[v]<0) return false ;
else if(!c[v]&&!dfs(v)) return false;
c[u]=1;
return true;
}
bool toposort()
{
memset(c,0,sizeof(c));
for(int u=1; u<=n; u++)
if(dfs(u)) return true;
return false;
}
int main()
{
int a,b;
while(cin>>n>>m)
{
memset(G,0,sizeof(G));
while(m--)
{
cin>>a>>b;
G[b][a]=1;
}
if(toposort()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}