HDU 5695 Gym Class 拓扑排序

本文提供了一道来自HDU在线评测系统的题目(PID 5695)的解答代码。该题通过使用优先队列实现拓扑排序的方法来解决,主要涉及图论中的有向图及其遍历算法。代码采用C++编写,利用了STL中的容器和算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5695

#include <bits/stdc++.h>
#define sf scanf
#define pf printf
typedef long long LL;
using namespace std;
const int maxn = 100000 + 5,INF = 2e9;
vector<int> _ADJ[maxn];
int ins[maxn],pos[maxn];

priority_queue<int> Q;
int main(){
    int T;sf("%d",&T);
    while( T-- ){
        int n,m;sf("%d %d",&n,&m);
        for(int i = 1;i <= n;++i) _ADJ[i].clear(),ins[i] = 0;
        for(int i = 0;i < m;++i){
            int u,v;sf("%d %d",&u,&v);
            _ADJ[u].push_back(v);ins[v]++;
        }
        for(int i = 1;i <= n;++i)
            if(ins[i] == 0) Q.push(i);
        int MIN = INF;
        LL ret = 0;
        for(int i = 1;i <= n;++i){
            pos[i] = Q.top();Q.pop();
            MIN = min(MIN,pos[i]);
            ret = ret + MIN;
            int len = _ADJ[pos[i]].size();
            for(int j = 0;j < len;++j){
                ins[_ADJ[pos[i]][j]]--;
                if(ins[_ADJ[pos[i]][j]] == 0) Q.push(_ADJ[pos[i]][j]);
            }
        }
        pf("%lld\n",ret);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值