HDU 5695 Gym Class 拓扑排序

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5695

题意:

题解:

如果A不想让B在他的前面,那么就可以认为A到B有一条有向边,那么就可以利用拓扑序列来做这道题了,但是要想每次首先访问到的是能访问到的中的最大值,那么可以把入度为零的所有点压入优先队列中,使得每次新的拓展节点是能拓展的种的最大值.

代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 #define MS(a) memset(a,0,sizeof(a))
 5 #define MP make_pair
 6 #define PB push_back
 7 const int INF = 0x3f3f3f3f;
 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 9 inline ll read(){
10     ll x=0,f=1;char ch=getchar();
11     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
12     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
13     return x*f;
14 }
15 //
16 const int maxn = 1e5+10;
17 
18 vector<int> v[maxn];
19 int d[maxn];
20 
21 int main(){
22     int T = read();
23     while(T--){
24         MS(d);
25         int n,m; scanf("%d%d",&n,&m);
26         for(int i=0; i<=n; i++) v[i].clear();
27         for(int i=0; i<m; i++){
28             int a,b; scanf("%d%d",&a,&b);
29             v[a].push_back(b);
30             d[b]++;
31         }
32         priority_queue<int> pq;
33         int minn = n+1;
34         for(int i=1; i<=n; i++) if(d[i]==0)
35             pq.push(i);
36 
37         ll ans = 0;
38         while(!pq.empty()){
39             int t = pq.top(); pq.pop();
40             minn = min(minn,t);
41             ans += minn;
42             for(int i=0; i<(int)v[t].size(); i++){
43                 --d[v[t][i]];
44                 if(d[v[t][i]] == 0)
45                     pq.push(v[t][i]);
46             }
47         }
48 
49         cout << ans << endl;
50     }
51 
52     return 0;
53 }

 

转载于:https://www.cnblogs.com/yxg123123/p/6827612.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值