博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BZOJ4010 HNOI2015 菜肴制作 拓扑排序+贪心
阅读量:4677 次
发布时间:2019-06-09

本文共 1216 字,大约阅读时间需要 4 分钟。

题意:给定限制条件(a,b)表示a必须在b之前,求所有合法序列中,小的数尽量在前面的方案

题解:首先我们根据限制条件建反向图,然后在反向图上求字典序最小的拓扑序(队列改为堆),逆序输出即可。

#include 
#include
#include
#include
#include
#include
#include
using namespace std;const int MAXN=100000+2;struct HASH{ int u; HASH *next; HASH(){} HASH(int _u,HASH *_next):u(_u),next(_next){}}*table[MAXN],mem[MAXN*2];int N,M,Q,cnt,ans[MAXN],degree[MAXN];priority_queue
q;void Insert(int u,int v){ table[u]=&(mem[cnt++]=HASH(v,table[u]));}void Topology_Sort(){ while(!q.empty()) q.pop(); for(int i=1;i<=N;i++) if(!degree[i]) q.push(i); while(!q.empty()){ ans[++cnt]=q.top(),q.pop(); for(HASH *p=table[ans[cnt]];p;p=p->next){ degree[p->u]--; if(!degree[p->u]) q.push(p->u); } }}int main(){ scanf("%d",&Q); while(Q--){ memset(table,0,sizeof(table)); memset(degree,0,sizeof(degree)); cnt=0; scanf("%d %d",&N,&M); for(int i=1,u,v;i<=M;i++){ scanf("%d %d",&u,&v); Insert(v,u),degree[u]++; } cnt=0,Topology_Sort(); if(cnt!=N) printf("Impossible!\n"); else{ for(int i=N;i;i--) printf("%d ",ans[i]); printf("\n"); } } return 0;}
View Code

 

转载于:https://www.cnblogs.com/WDZRMPCBIT/p/6476760.html

你可能感兴趣的文章
项目杂记(MONTHS_BETWEEN,Having ,Spool)
查看>>
cmd ora-12560协议适配器错误
查看>>
Linux压缩解压缩(unzip,tar)
查看>>
kafka 在阿里云部署
查看>>
yum 命令下载安装Openjdk
查看>>
Hyperic
查看>>
(转)SimpleDateFormat使用
查看>>
设计模式有感
查看>>
react-native android 初始化问题
查看>>
最后一周总结
查看>>
教大家怎么给博客添加一个看板娘
查看>>
[设计模式]4、设计模式之工厂设计模式
查看>>
从尾到头打印链表(c++实现)
查看>>
videojs 播放 rtmp 感悟
查看>>
胖子哥的大数据之路(15):互联网企业数据战略运营规划之总决式
查看>>
popen() 使用举例 (转载)
查看>>
NSString的常用方法
查看>>
在Xcode中使用Git进行源码版本控制
查看>>
教程Xcode 下编译发布与提交App到AppStore
查看>>
指针链
查看>>