HDU 4857 (反向拓扑排序 + 优先队列)

糟糕的事情发生啦,现在大家都忙着逃命。但是逃命的通道很窄,大家只能排成一行。

现在有n个人,从1标号到n。同时有一些奇怪的约束条件,每个都形如:a必须在b之前。

同时,社会是不平等的,这些人有的穷有的富。1号最富,2号第二富,以此类推。有钱人就贿赂负责人,所以他们有一些好处。

负责人现在可以安排大家排队的顺序,由于收了好处,所以他要让1号尽量靠前,如果此时还有多种情况,就再让2号尽量靠前,如果还有多种情况,就让3号尽量靠前,以此类推。

那么你就要安排大家的顺序。我们保证一定有解。

Input

第一行一个整数T(1 <= T <= 5),表示测试数据的个数。

然后对于每个测试数据,第一行有两个整数n(1 <= n <= 30000)和m(1 <= m <= 100000),分别表示人数和约束的个数。

然后m行,每行两个整数a和b,表示有一个约束a号必须在b号之前。a和b必然不同。

Output

对每个测试数据,输出一行排队的顺序,用空格隔开。

Sample Input

1

5 10

3 5

1 4

2 5

1 2

3 4

1 4

2 3

1 5

3 5

1 2

Sample Output

1 2 3 4 5

题解:拓扑排序,反向输出这个视频讲解的很好

#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<algorithm>
#include<string>
#include<algorithm>
using namespace std;
vector<int>G[30010];
int out[30010];
int a[30010];
void toposort(int n)
{
int len=n; priority_queue<int>q;
for(int i=1;i<=n;i++)
{
if(out[i]==0)
q.push(i);
}//找最后的那个点
while(!q.empty() )
{
int tmp=q.top();
a[len--]=tmp;
q.pop();
for(int i=0;i<G[tmp].size();i++)//找有第一个点相连的点,处理一下
{
out[G[tmp][i]]--;
if(out[G[tmp][i]]==0)
q.push(G[tmp][i]); //入队列
}
}
for(int i=1;i<n;i++)
printf("%d ",a[i]);
printf("%d\n",a[n]); } int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
for(int i=0;i<=n;i++)
{
out[i]=0;
G[i].clear() ;
}
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
G[b].push_back(a);
out[a]++;
}
toposort(n);
}
return 0;
}

最新文章

  1. css优化篇
  2. The Joys of Conjugate Priors
  3. js 函数定义三种方式
  4. 调试工具GDB详解
  5. GC日志介绍
  6. powerdesigner使用之——从“概念模型”到“物理模型”
  7. C# 任意类型数据转JSON格式(转)
  8. Masonry约束崩溃
  9. 032数值的整数次方(keep it up)
  10. ubuntu14.04折腾迅雷xware
  11. Android System Property 解析
  12. PHP实现二维数组排序(按照数组中的某个字段)
  13. DataInputStream EOFEXCEPTION
  14. phpstudy最新版中php5.6版报错
  15. MySQL Backup myloader
  16. MM-实际应用中的难题
  17. python 取整itertools
  18. web页面相关的一些常见可用字符介绍——张鑫旭
  19. 多线程demo,订单重复支付
  20. 记一次生产环境axis2服务特别慢的问题。

热门文章

  1. linux 解决 gvfsd-smb-browse CPU 100%占用
  2. windows无法连接到打印机 操作失败,错误为0x00000002 解决方案
  3. Java笔记--动态代理
  4. sql &amp; sqlalchemy join多个表
  5. jquery mmgrid使用
  6. vs移动团队项目集合
  7. map侧连接
  8. 关于Vue生命周期的小记录
  9. CRM User Status profile中Business Transaction字段的用途
  10. UVA 10375 Choose and divide(大数的表示)