【POJ 3687】Labeling Balls (拓扑排序)
来源:互联网 发布:淘宝客单页网站源码 编辑:程序博客网 时间:2024/06/01 22:19
传送门
Labeling Balls
题意:按照拓扑序输出序列,在多解时先保证1的序号最小,然后是2的序号最小,3的……
I think
拓扑排序(反向建边+建立大根堆维护入度为 0的栈内元素)若正向建边+维护小根堆,每次取出最小的元素只能保证它满足当前最小 ,不一定是整体最小,但反向建边+维护大根堆可以通过每次取最大元素使得最小元素从整体上看尽可能置后 ,最后反向输出答案即可。
Code
#include<cstdio>#include<cstring>using namespace std;const int sm = 2e2+5;const int sn = 4e4+5;int N,M,tot,cnt;int to[sn],nxt[sn],hd[sm];int rec[sm],rd[sm];bool flag;void Swap(int &x,int &y) { int t=x;x=y;y=t; } void Add(int u,int v) { to[++tot]=v,nxt[tot]=hd[u],hd[u]=tot,rd[v]++;}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 t=Q[1]; Q[1]=Q[sz--]; int now=1,next; while((now<<1)<=sz) { next=now<<1; if(next+1<=sz&&Q[next+1]>Q[next]) ++next; if(Q[now]>Q[next]) break; Swap(Q[now],Q[next]); now=next; } return t;}int main() { int u,v,t,T; read(T); while(T--) { read(N),read(M); flag=tot=cnt=sz=0; for(int i=1;i<=N;++i) hd[i]=rd[i]=0; for(int i=1;i<=M;++i) { read(u),read(v); if(u==v)flag=1; Add(v,u); } if(flag) { puts("-1"); continue; } for(int i=N;i>=1;--i) if(rd[i]==0) Push(i); cnt=N; while(sz) { t=Pop(); rec[t]=cnt--; for(int i=hd[t];i;i=nxt[i]) { rd[to[i]]--; if(rd[to[i]]==0) Push(to[i]); } } if(cnt) puts("-1"); else { printf("%d",rec[1]); for(int i=2;i<=N;++i) printf(" %d",rec[i]); putchar(10); } } return 0;}
阅读全文
0 0
- poj 3687 Labeling Balls(拓扑排序)
- POJ 3687 Labeling Balls 拓扑排序
- poj 3687 【拓扑排序】【Labeling Balls】
- poj Labeling Balls 3687 拓扑排序!!!!
- poj 3687 Labeling Balls 拓扑排序
- POJ 3687Labeling Balls(拓扑排序)
- POJ 3687 Labeling Balls 拓扑排序
- poj 3687 Labeling Balls ( 拓扑排序 )
- Poj 3687 Labeling Balls[拓扑排序]
- Poj 3687 Labeling Balls (拓扑排序)
- poj 3687 Labeling Balls(拓扑排序)
- [POJ 3687] Labeling Balls [拓扑排序]
- POJ 3687 Labeling Balls(拓扑排序)
- poj 3687 Labeling Balls 拓扑排序
- POJ 3687-Labeling Balls(逆序拓扑排序)
- POJ 3687 Labeling Balls 逆向拓扑排序
- poj 3687 Labeling Balls(拓扑排序)
- **poj 3687 Labeling Balls (*拓扑排序)
- Js制作简单的网页
- 笨方法学Python 习题 46: 一个项目骨架
- hdu6119 小小粉丝度度熊【尺取】
- 腾讯云系列三:Centos7 安装 mysql数据库 远程连接 字符集设置
- 结构体的大小
- 【POJ 3687】Labeling Balls (拓扑排序)
- 博弈
- Java--正则表达式(五)
- html,css学习笔记
- Faster R-CNN——ROIDB和Minibatch函数调用分析
- java数据结构与算法之平衡二叉树(AVL树)的设计与实现
- 并查集入门--hd 2079 并查集模板
- div图片水平垂直居中不随滚动条滚动的CSS代码(兼容IE8+)
- 锁、PV操作、进程互斥与同步的实现