【模版】拓扑排序

Kahn算法

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<stack>
using namespace std;
const int maxn=10000+5;
int n,m,tot,head[maxn],rd[maxn],a[maxn];
struct Edge{
	int next,to;
}e[maxn];
void Add(int x,int y){
	e[++tot].next=head[x];
	e[tot].to=y;
	head[x]=tot;
} 
void Kahn(){
	stack<int> sta;
	for(int i=1;i<=n;i++){
		if(!rd[i])sta.push(i);
	}
	int cnt=0;
	while(!sta.empty()){
		int u=sta.top();sta.pop();a[++cnt]=u;
		for(int x=head[u];x;x=e[x].next){
			int v=e[x].to;
			rd[v]--;
			if(!rd[v])sta.push(v);
		}
	}
	if(cnt<n){
		cout<<"Cycle"<<endl;
		return;
	}
	for(int i=1;i<=cnt;i++)cout<<a[i]<<" ";
}

int main(){
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int x,y;cin>>x>>y;
		Add(x,y);rd[y]++;
	}
	Kahn();
}

DFS拓扑

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<stack>
using namespace std;
const int maxn=10000+5;
int n,m,tot,cycle,vis[maxn],head[maxn],rd[maxn],a[maxn];
stack<int> sta;
struct Edge{
	int next,to;
}e[maxn];
void Add(int x,int y){
	e[++tot].next=head[x];
	e[tot].to=y;
	head[x]=tot;
} 
void dfs(int u){
	if(cycle==1)return;
	vis[u]=-1;
	for(int x=head[u];x;x=e[x].next){
		int v=e[x].to;
		if(!vis[v])dfs(v);
		else if(vis[v]==-1){
			cout<<"Cycle"<<endl;
			cycle=1;
			return;
		}
	}
	vis[u]=1;sta.push(u);
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int x,y;cin>>x>>y;
		Add(x,y);rd[y]++;
	}
	for(int i=1;i<=n;i++){
		if(!rd[i])dfs(i);
	}
	if(cycle==0){
		while(!sta.empty())cout<<sta.top()<<' ',sta.pop();
	}
}

DP+拓扑

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<stack>
using namespace std;
const int maxn=1e4+5;
int n,m,len,cnt,tot,head[maxn],rd[maxn],f[maxn];
struct Edge{
	int next,to,w;
}e[maxn];
void Kahn(){
	stack<int> sta;
	for(int i=0;i<n;i++){
		if(!rd[i])sta.push(i),f[i]=1;
		else f[i]=0;
	}
	int ans=1;
	while(!sta.empty()){
		int u=sta.top();sta.pop();
		for(int x=head[u];x;x=e[x].next){
			int v=e[x].to,w=e[x].w;rd[v]--;
			f[v]=max(f[v],f[u]+w);
			ans=max(ans,f[v]);
			if(!rd[v])sta.push(v);
		}
	}
	cout<<ans<<endl;
}
void Add(int x,int y,int z){
	e[++tot].next=head[x];
	e[tot].to=y;
	e[tot].w=z;
	head[x]=tot;
}
int main(){
	while(scanf("%d%d",&n,&m)==2){
		memset(head,0,sizeof(head));
		memset(rd,0,sizeof(rd));
		len=0;
		for(int i=1;i<=m;i++){
			int x,y,z;cin>>x>>y>>z;
			Add(x,y,z);rd[y]++;
		}
	}
	Kahn();
}
原文地址:https://www.cnblogs.com/614685877--aakennes/p/12995137.html