【POJ 1094】Sorting it all out (拓扑排序)
来源:互联网 发布:ubuntu 32位iso下载 编辑:程序博客网 时间:2024/05/22 07:56
传送门
Sorting it all out
题意:判断题给条件能否得出唯一拓扑序且无环,若是则按拓扑序输出序列顺序,否则按照要求输出。
I think
每输入一条边跑一次拓扑 ,任意拓扑过程中若存在环,则入栈元素数 < N,任意时刻若栈中超过一个元素,则暂不能确定顺序。 若可以确定顺序且无环,则添加完当前边确定唯一拓扑序 。
Code
#include<cstdio>using namespace std;const int sm = 1e5+5;int T,N,M,cnt,tot;int to[sm],hd[sm],nxt[sm];int stk[sm],rd[sm],rec[sm];void Swap(int &x,int &y) { int t=x;x=y;y=t; }void read(int &x) { char ch=getchar();x=0; while(ch>'9'||ch<'0') ch=getchar(); while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();} int sz;int Q[sm];void Push(int x) { int now,next; Q[++sz]=x; now=sz; while(now>1) { next=now>>1; if(Q[next]>Q[now]) break; Swap(Q[next],Q[now]); now=next; }}int Pop() { int now,next,t; t=Q[1]; Q[1]=Q[sz--]; now=1; while((now<<1)<=sz) { next=now<<1; if(next+1<=sz&&Q[next+1]>Q[next]) ++next; if(Q[next]<Q[now]) break; Swap(Q[next],Q[now]); now=next; } return t;}void Add(int u,int v) { to[++tot]=v,nxt[tot]=hd[u],hd[u]=tot,rd[v]++;}int main() { int u,v,t; read(T); while(T--) { read(N),read(M); tot=sz=0,cnt=N; for(int i=1;i<=N;++i) hd[i]=rd[i]=0; for(int i=1;i<=M;++i) { read(u),read(v); Add(v,u); } for(int i=N;i>=1;--i) if(rd[i]==0) Push(i); while(sz) { t=Pop(); rec[cnt--]=t; for(int i=hd[t];i;i=nxt[i]) { rd[to[i]]--; if(rd[to[i]]==0) Push(to[i]); } } if(cnt) puts("Impossible!"); else { for(int i=1;i<=N;++i) printf("%d ",rec[i]); putchar(10); } } return 0;}
阅读全文
0 0
- POJ 1094 Sorting It All Out(拓扑排序)
- Poj 1094-Sorting It All Out [拓扑排序]
- POJ 1094-Sorting It All Out 拓扑排序
- zoj 1060 || poj 1094 Sorting It All Out(拓扑排序)
- POJ 1094 Sorting It All Out 拓扑排序
- POJ 1094 Sorting It All Out 拓扑排序
- POJ 1094 Sorting It All Out 拓扑排序
- poj 1094 Sorting It All Out 拓扑排序
- POJ 1094 Sorting It All Out (拓扑排序)
- POJ 1094 Sorting It All Out 拓扑排序
- poj 1094 Sorting It All Out(拓扑排序)
- poj 1094 Sorting It All Out 拓扑排序
- poj 1094 Sorting It All Out 拓扑排序
- poj 1094 Sorting It All Out (拓扑排序)
- poj 1094 Sorting It All Out (拓扑排序)
- Poj 1094 Sorting It All Out——拓扑排序
- POJ 1094 Sorting It All Out 拓扑排序+Floyd算法
- POJ 1094 Sorting It All Out (拓扑排序) - from lanshui_Yang
- codevs1298 凸包周长 解题报告
- PopuWindow用法
- WCF绑定netTcpBinding寄宿到控制台应用程序
- 袋鼠过河
- oracle增删改查语法
- 【POJ 1094】Sorting it all out (拓扑排序)
- 转载技巧~
- 【微信小程序】Page not found 错误
- 516_fragment不要用构造函数传参数
- 访问修饰符
- Divisible [数学]
- Single Number leetcode java
- Sequence I
- 使用turtle库画蛇