Minimal Labels

Minimal Labels

这个题需要用到拓扑排序的思维,但是这个题还有一个条件——字典序最小,因此可以用一个递增的优先队列来维护,每找到一个入度为 0 的点就把它 push 进去因而每一次判断的点总是当前入度为 0 的字典序最小的点。

代码:

// Created by CAD on 2019/8/6.
#include <bits/stdc++.h>

#define ll long long
#define fi first
#define se second
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f
#define PII pair<int,int>
#define PIII pair<pair<int,int>,int>
#define mst(name, value) memset(name,value,sizeof(name))
#define FOPEN freopen("C:\\Users\\14016\\Desktop\\cad.txt","r",stdin)
#define test(n) cout<<n<<endl
using namespace std;

priority_queue<int> q;
const int maxn = 2e5 + 5;
int cnt[maxn];
vector<int> g[maxn];
int a[maxn];

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1, u, v; i <= m; ++i)
    {
        cin >> u >> v;
        g[v].emplace_back(u);
        cnt[u]++;
    }
    for (int i = 1; i <= n; ++i) if (cnt[i] == 0) q.push(i);
    int ans = n;
    while (!q.empty())
    {
        int now = q.top();
        q.pop();
        a[now] = ans--;
        for (auto i:g[now])
            if (--cnt[i] == 0) q.push(i);
    }
    for (int i = 1; i <= n; ++i)
    {
        printf("%d%c", a[i], " \n"[i == n]);
    }
}

猜你喜欢

转载自www.cnblogs.com/CADCADCAD/p/11313729.html