HDU.3342 Legal or Not (拓扑排序 TopSort)
题意分析
裸的拓扑排序 根据是否成环来判断是否合法
详解请移步
算法学习 拓扑排序(TopSort)
代码总览
#include <iostream>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#define nmax 200
#define MEM(x) memset(x,0,sizeof(x))
using namespace std;
int n,m;
int indegree[nmax];
vector<int> v[nmax];
bool suc = true;
void topsort()
{
int cnt = 0;
queue<int> q;
while(1){
for(int i = 0; i<n; ++i){
if(indegree[i] == 0){
q.push(i);
cnt++;
indegree[i] = -1;
}
}
if(q.empty()) break;
while(!q.empty()){
int t = q.front();q.pop();
for(int i = 0; i<v[t].size();++i){
int tt = v[t][i];
if(indegree[tt] == -1){
suc =false;
break;
}else
indegree[tt]--;
}
if(!suc) break;
}
if(!suc) break;
}
if(suc && cnt!=n) suc = false;
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&m) == 2 && n){
MEM(indegree);
suc = true;
for(int i = 0; i<n;++i) v[i].clear();
for(int i = 0; i<m; ++i){
int a,b;
scanf("%d%d",&a,&b);
indegree[b]++;
v[a].push_back(b);
}
topsort();
printf("%s
",suc?"YES":"NO");
}
return 0;
}