hdu 4857 逃生【反向拓扑排序】

本文提供了一道名为HDU 4857的在线评测题目解决方案,采用逆向建立边关系的方式进行拓扑排序,并通过优先队列实现。详细解析了代码结构与算法思路。

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

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

题意:中文不解释

解法:

input:
1
3 1
3 1
answer:
3 1 2
而不是
2 3 1
所以逆向建边 拓扑

代码:

#include<stdio.h>
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<string.h>

using namespace std;

int n, m;
int a, b;
int in[30010];
int ans[30010];
vector<int> g[30010];

struct cmp
{
    bool operator()(int &a, int &b)
    {
        return a < b;
    }
};

int main()
{
    int t;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d%d",&n,&m);
        memset(in, 0, sizeof(in));
        for (int i = 1; i <= n; i++) g[i].clear();
        while (m--)
        {
            scanf("%d%d",&a,&b);
            g[b].push_back(a);
            in[a]++;
        }
        priority_queue<int,vector<int>,cmp> que;
        while (!que.empty()) que.pop();
        for (int i = 1; i <= n; i++)
            if (in[i] == 0) que.push(i);
        int cnt = 0;
        while (!que.empty())
        {
            int t = que.top(); que.pop();
            ans[cnt++] = t;
            for (int i = 0; i < g[t].size(); i++)
            {
                in[g[t][i]] --;
                if (in[g[t][i]] == 0)
                    que.push(g[t][i]);
            }
        }
        for (int i = cnt - 1; i >= 0; i--)
        {
            printf("%d",ans[i]); 
            if (i == 0) printf("\n"); else printf(" ");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值