欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU3342拓扑排序

程序员文章站 2022-03-14 20:06:50
...
方法一: 
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<set>
#include<vector>
using namespace std;
typedef long long ll;
const int maxx=105;
int n,m;
int indegree[maxx];
int a[maxx];
vector<int>ans[maxx];
int k;
void Topsort(int n){
	int index;
	int m=0;
	for(int i=0;i<n;i++){
		m=0;
		for(int j=0;j<n;j++){
			if(indegree[j]==0){
				index=j;
				m++;
			}
		}
		if(m==0)break;
		a[++k]=index;
		indegree[index]=-1;
		for(int j=0;j<ans[index].size();j++){
			int t=ans[index][j];
			indegree[t]--;
		}
	}
}
int main(){
	while(scanf("%d %d",&n,&m)){
		if(n==0&&m==0)break;
		memset(indegree,0,sizeof(indegree));
		memset(a,0,sizeof(a));
		for(int i=0;i<=n;i++){
			ans[i].clear();
		}
		for(int i=1;i<=m;i++){
			int x,y;
			scanf("%d %d",&x,&y);
			ans[x].push_back(y);
			indegree[y]++;
		}
		k=0;
		Topsort(n);
		if(k==n){
			cout<<"YES"<<endl;
		}else{
			cout<<"NO"<<endl;
		}
	}
	return 0;
} 
方法二: 
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
using namespace std;
const int maxx=1e3+10;
int vis[maxx][maxx];
int indegree[maxx];
int n,m;
vector<int>ans[maxx];
int a[maxx];
int main(){
	while(scanf("%d %d",&n,&m)!=EOF){
		if(n==0&&m==0)break;
		memset(indegree,0,sizeof(indegree));
		memset(vis,0,sizeof(vis));
		for(int i=0;i<=n;i++){
			ans[i].clear();
		}
		for(int i=1;i<=m;i++){
			int x,y;
			scanf("%d %d",&x,&y);
			ans[x].push_back(y);
			indegree[y]++;
		}
		queue<int>q;
		for(int i=0;i<n;i++){
			if(indegree[i]==0){
				q.push(i);
			}
		}
		int k=0;
		while(!q.empty()){
			int u=q.front();
			q.pop();
			a[++k]=u;
			for(int i=0;i<ans[u].size();i++){
				int t=ans[u][i];
				indegree[t]--;
				if(indegree[t]==0){
					q.push(t);
				}
			}
		}
		if(k==n){
			cout<<"YES"<<endl; 
		}else{
			cout<<"NO"<<endl;
		}
	}
	return 0;
}