cf Educational Codeforces Round 25 E - Minimal Labels

原题:
E. Minimal Labels
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.

You should assign labels to all vertices in such a way that:

Labels form a valid permutation of length n — an integer sequence such that each integer from 1 to n appears exactly once in it.
If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu.
Permutation should be lexicographically smallest among all suitable.
Find such sequence of labels to satisfy all the conditions.

Input
The first line contains two integer numbers n, m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105).

Next m lines contain two integer numbers v and u (1 ≤ v, u ≤ n, v ≠ u) — edges of the graph. Edges are directed, graph doesn’t contain loops or multiple edges.

Output
Print n numbers — lexicographically smallest correct permutation of labels of vertices.

Examples
input
3 3
1 2
1 3
3 2
output
1 3 2
input
4 5
3 1
4 1
2 3
3 4
2 4
output
4 1 2 3
input
5 4
3 1
2 1
2 3
4 5
output
3 1 2 4 5

中文:
给你一个有向无环图,让你给每个节点标号,被指向的节点的标号要小于指向它的节点。输出字典序最小的标号顺序。

#include<bits/stdc++.h>
using namespace std;
int n, m;
int deg[100001];
vector<int> gra[100001];
int ans[100001];

void topsort()
{
    memset(ans, 0, sizeof(ans));
    priority_queue<int, vector<int>, less<int> > q;
    int cnt = n;
    for (int i = 1; i <= n; i++)
        if (deg[i] == 0)
        {
            q.push(i);
        }

    while (!q.empty())
    {
        int h = q.top();
        q.pop();

        ans[h] = cnt--;
        if (gra[h].size() == 0)
            continue;
        for(int i=0;i<gra[h].size();i++)
        {
            if(--deg[gra[h][i]]==0)
                q.push(gra[h][i]);
        }
    }

}


int main()
{
    ios::sync_with_stdio(false);
    while (cin >> n >> m)
    {
        memset(gra, 0, sizeof(gra));
        memset(deg, 0, sizeof(deg));
        for (int i = 1; i <= n; i++)
            gra[i].clear();
        for (int i = 0; i<m; i++)
        {
            int a, b;
            cin >> a >> b;
            gra[b].push_back(a);
            deg[a]++;
        }
        topsort();

        for (int i = 1; i <= n; i++)
            if (i != n)
                cout << ans[i] << " ";
            else
                cout << ans[i] << endl;
    }
    return 0;
}

解答:

首先由题目可以得知,入度为0的节点都拿出来,按照字典序排列,然后把由此节点出去的边全部去掉。再重复上面的过程即可。可知,就是拓扑排序的过程。

cf上的e题居然是裸的拓扑排序,把我弄一愣。

但是这题也有点小弯。

使用队列的拓扑排序算法要使用优先队列,其次,要反着去找,即每次找入度最大的,入度最大的元素一定排在最后面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值