HDU 5695 Gym Class(拓扑排序、优先队列)

博客介绍了HDU 5695 Gym Class问题,该问题要求找到权值和最大的拓扑排序。权值定义为元素在其前包括自身的最小数。解决方案利用了拓扑排序和优先队列,确保在度为0的节点中选择编号最大的节点,以最大化权值和。数据规模为n≤105, m≤105。" 130308670,18277175,Spring MVC中Model、Map、ModelMap与ModelAndView解析,"['spring', 'java', 'Web开发', 'MVC框架']

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

题目链接;
HDU 5695 Gym Class
题意:
定义序列每个元素的权值是在他之前包括自己的最小数。求序列权值和最大的拓扑排序。
数据范围: n105,m105
分析;
也就是每次从度为 0 <script type="math/tex" id="MathJax-Element-74">0</script>的点中我们尽可能要得到编号大的点。优先队列搞下就好了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#include <vector>
#include <queue>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 100010;

int degree[MAX_N], ans[MAX_N];
vector<int> vec[MAX_N];
priority_queue<int> que;

void TopoSort(int n)
{
    for(int i = 1; i <= n; ++i) {
        if(degree[i] == 0) que.push(i);
    }
    int total = 1;
    while(!que.empty()) {
        int cur = que.top();
        que.pop();
        ans[total++] = cur;
        for(int i = 0; i < vec[cur].size(); ++i) {
            int to = vec[cur][i];
            degree[to]--;
            if(degree[to] == 0) que.push(to);
        }
    }
}

int main()
{
    int T, n, m;
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &n, &m);
        for(int i = 0; i <= n; ++i) {
            degree[i] = 0;
            vec[i].clear();
        }
        for(int i = 0; i < m; ++i) {
            int u, v;
            scanf("%d%d", &u, &v);
            degree[v]++;
            vec[u].push_back(v);
        }
        TopoSort(n);
        ll sum = ans[1];
        for(int i = 2; i <= n; ++i) {
            ans[i] = min(ans[i], ans[i - 1]);
            sum += ans[i];
        }
        printf("%lld\n", sum);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值