Codeforces 825 F Minimal Labels(反向拓扑排序)

来源:互联网 发布:SEO优化 编辑:程序博客网 时间:2024/06/05 05:20

题目地址:http://codeforces.com/contest/825/problem/E
题意:给出一个有n个顶点和m个边的有向非循环图。任何一对顶点之间不存在自环或多边,要为所有顶点分配标签,要求如下:

  • 标签形成长度为n的整数序列的有效排列,使得从1到n的每个整数在其中出现一次。
  • 如果存在从顶点v到顶点u的边缘,那么标签v应该小于标签u。
  • 输出的排列应该是字典序最小的。

思路:一看到题目就想到是拓扑排序的题目,因为后面排到的序号小的优先级比前面排到的序号大的优先级高,所以可以反向拓扑排序。

#include <iostream>#include <cstring>#include <string>#include <queue>#include <vector>#include <map>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <algorithm>#define LL long long #define N 100010#define M 50010#define inf 0x3f3f3f3f3f3f3f3fusing namespace std;const LL mod = 1e9 + 7;const double eps = 1e-9;vector<int> mapp[N];int n, m, ans;int in[N], num[N];void init() {    for (int i = 0; i <= n; i++) {        mapp[i].clear();    }    memset(in, 0, sizeof(in));    ans = n;}void topu() {    int vis[N];    memset(vis, false, sizeof(vis));    priority_queue<int> q;    for (int i = 1; i <= n; i++) {        if (in[i] == 0) {            q.push(i);            vis[i] = true;        }    }    while (!q.empty()) {        int x = q.top();        q.pop();        num[x] = ans--;        for (int i = 0; i < mapp[x].size(); i++) {            int y = mapp[x][i];            if (vis[y]) {                continue;            }            in[y]--;            if (in[y] == 0) {                q.push(y);                vis[y] = true;            }        }    }}int main() {    cin.sync_with_stdio(false);    int a, b;    while (cin >> n >> m) {        init();        for (int i = 0; i < m; i++) {            cin >> a >> b;            mapp[b].push_back(a);            in[a]++;        }        topu();        for (int i = 1; i <= n; i++) {            cout << num[i] << " ";        }        cout << endl;    }    return 0;}
原创粉丝点击