您的位置:首页 > 其它

拓扑排序模板

2016-02-22 17:40 357 查看
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
struct edge{
int w,next;
}e[10000];
stack <int> s;
int n,m,cnt=1,ans;
int head[1000],d[1000],f[1000];
void adde(int u,int w)
{
e[cnt].w=w;
e[cnt].next=head[u];
head[u]=cnt++;
d[w]++;
}
bool topsort()
{
for(int i=1;i<=n;i++)
if(!d[i]) s.push(i);
while(!s.empty())
{
int k=s.top();s.pop();
ans++;
f[ans]=k;
for(int u=head[k];u!=-1;u=e[u].next)
{
d[e[u].w]--;
if(!d[e[u].w]) s.push(e[u].w);
}
}
if(ans==n) return 1;
else return 0;
}
int main()
{
int u,w,v;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)//建图
{
scanf("%d%d",&u,&w);
adde(u,w);
}
if(topsort())
{
for(int i=1;i<=ans;i++) printf("%d ",f[i]);
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: