例题11.8Legal or Not
//很基础的拓扑排序题:判断是否是有环图
#include
#include
#include
#include
using namespace std;
vector graph[101];
int indegree[101];
int TuoPu(int n)
{
queue q;
for(int i=0;i {
if(indegree[i]==0)q.push(i);
}
int ans=0;
while(!q.empty())
{
int u=q.front();
q.pop();
ans++;
for(int i=0;i {
int v=graph[u][i];
indegree[v]--;
if(indegree[v]==0)q.push(v);
}
}
return ans;
}
int main()
{
int n,m;
while(cin>>n)
{
if(n==0)break;
cin>>m;
memset(indegree,0,sizeof(indegree));
memset(graph,0,sizeof(graph));
for(int i=1;i<=m;i++)
{
int f,t;cin>>f>>t;
graph[f].push_back(t);
indegree[t]++;
}
int ans=TuoPu(n);
if(ans==0)cout<<"NO"< else cout<<"YES"< }
}
#include
#include
#include
#include
using namespace std;
vector
int indegree[101];
int TuoPu(int n)
{
queue
for(int i=0;i
if(indegree[i]==0)q.push(i);
}
int ans=0;
while(!q.empty())
{
int u=q.front();
q.pop();
ans++;
for(int i=0;i
int v=graph[u][i];
indegree[v]--;
if(indegree[v]==0)q.push(v);
}
}
return ans;
}
int main()
{
int n,m;
while(cin>>n)
{
if(n==0)break;
cin>>m;
memset(indegree,0,sizeof(indegree));
memset(graph,0,sizeof(graph));
for(int i=1;i<=m;i++)
{
int f,t;cin>>f>>t;
graph[f].push_back(t);
indegree[t]++;
}
int ans=TuoPu(n);
if(ans==0)cout<<"NO"<
}
全部评论
相关推荐