CF-825E Minimal Labels 反向拓扑排序

http://codeforces.com/contest/825/problem/E

一道裸的拓扑排序题。为什么需要反向拓扑排序呢?因为一条大下标指向小下标的边可能会导致小下标更晚分配到号码,导致字典序增大。而反向拓扑排序在上述情况,只会使大序号更晚分配到序号,而小序号还是较小的,根据字典序比对规则,当然是选择反向拓扑排序啦。

#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#define N 200005
using namespace std;
int n, m, sum, cnt, flag;
int deg[N];
int head[N];
struct Node
{
    int v, next;
};
struct cmp
{
    bool operator()(int a, int b)
    {
        return a<b;
    }
};
int k;
int ans[N];
Node edge[N << 1];
void print(int num)
{
    ans[num] = k--;
}
void topoSort(int n)
{
    priority_queue<int, vector<int>, cmp> q;
    for (int i = 1; i <= n; i++)
        if (deg[i] == 0)
            q.push(i), deg[i]--;
    //cout << q.size() << endl;
    while (!q.empty())
    {
        int u = q.top();
        q.pop(), print(u);
        sum--;
        for (int i = head[u]; i != -1; i = edge[i].next)
        {
            Node e = edge[i];
            deg[e.v]--;
            if (deg[e.v] == 0) q.push(e.v), deg[e.v]--;
            
        }
    }
}
void ini()
{
    for (int i = 1; i <= n; i++)
        deg[i] = 0, head[i] = -1, flag = 0;
    cnt = 0, sum = n;
}
void add(int u, int v)
{
    swap(u, v);
    deg[v]++;
    edge[cnt].v = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
int main(int argc, const char * argv[]) {
    while (scanf("%d%d", &n, &m) != EOF)
    {
        k = n;
        int a, b;
        ini();
        for (int i = 0; i<m; i++)
            scanf("%d%d", &a, &b), add(a, b);
        topoSort(n);
        for (int i = 1; i <= n; i++)
            printf("%d ", ans[i]);
        puts("");
    }
    return 0;
}

 

posted @ 2017-07-17 15:07  Luke_Ye  阅读(315)  评论(0编辑  收藏  举报