Educational Codeforces Round 25E. Minimal Labels(拓扑排序+思维)

E. Minimal Labels
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 nm (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 

题意:

n个点m条边的有向图,要给每个点从1-n编号,如果u->v有一条边,那么u的编号需要比v的编号小,每种编号只能用一次。输出n个点的编号且要求字典序最小。


分析:

正向的拓扑排序,优先去编号小的点赋上小的编号是不对的。因为当前入度为0的点掉其所有出边后,可能会有一些点入度为0,它们的编号比较大但相对于当前优先队列中的点,它们的编号是最小的,所以会导致优先为它们赋值上编号,实际上这样的贪心并不是最优的。

正确的做法是反向建边,然后拓扑排序过程中赋值。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
int n, m, in[maxn], ans[maxn];
vector<int> g[maxn];
int main()
{

    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        g[v].push_back(u);
        in[u]++;
    }
    priority_queue<int, vector<int>, less<int> > q;
    for(int i = 1; i <= n; i++)
        if(in[i] == 0)
            q.push(i);
    int cnt = n;
    while(!q.empty())
    {
        int v = q.top();
        q.pop();
        ans[v] = cnt--;
        for(int i = 0; i < g[v].size(); i++)
            if(!(--in[g[v][i]]))
                q.push(g[v][i]);
    }
    for(int i = 1; i <= n; i++)
        printf("%d ", ans[i]);
    return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值