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

来源:互联网 发布:linux和c语言的关系 编辑:程序博客网 时间:2024/06/05 03:56

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 31 21 33 2
output
1 3 2 
input
4 53 14 12 33 42 4
output
4 1 2 3 
input
5 43 12 12 34 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