POJ4857 逃生 —— 拓扑排序 特殊排序方式

14 篇文章 0 订阅

POJ4857 逃生

// Decline is inevitable, romance will last forever.
//#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string>
#include <cstdio>
using namespace std;
#define mst(a, x) memset(a, x, sizeof(a))
#define INF 0x3f3f3f3f
#define P 998244353
//#define int long long
const int maxn = 3e4 + 10;
const int maxm = 1e5 + 10;
int n, m;
struct Edge {
    int to, dis;
    Edge(int to, int dis) : to(to), dis(dis) {}
};
vector<Edge> edge[maxn];
int in[maxn];       //每个点的入度
vector<int> topo;       //存储拓扑排序顺序 按字典序由小到大
bool topo_() {
    topo.clear();
    priority_queue<int, vector<int> > q;
    while(!q.empty())  q.pop();
    for(int i = 1; i <= n; i++)
        if(!in[i]) q.push(i);   //把入度为0的点都加入
    while(!q.empty()) {
        int p = q.top();
        q.pop();
        topo.push_back(p);
        for(int i = 0; i < edge[p].size(); i++) {
            int y = edge[p][i].to;
            in[y]--;
            if(!in[y]) q.push(y);
        }
    }
    if(topo.size() != n)        //有环
        return false;
    return true;
}
void solve() {
    cin >> n >> m;
    mst(in, 0);
    for(int i = 0; i < maxn; i++)
        edge[i].clear();
    for(int i = 1; i <= m; i++){
        int u, v;
        cin >> u >> v;
        edge[v].push_back(Edge(u, 1));      //u在v之前
        in[u]++;
//        add_edge(v, u, 1), in[u]++; //v在u之前
    }
    if(!topo_())
        cout << "No Answer!" << endl;
    else {
        for(int i = topo.size()-1; i > 0; i--) {
            cout << topo[i] << ' ';
        }
        cout << topo[0] << endl;
    }
}
signed main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//    int T; scanf("%d", &T); while(T--)
    int T; cin >> T; while(T--)
    solve();
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值