CF825E:Minimal Labels(拓扑排序)

来源:互联网 发布:十香cosplay淘宝 编辑:程序博客网 时间:2024/06/05 09:20

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条边的有向图,要你为这N个节点编号为1~N,要求①子节点的编号要比其父节点大,②最后的编号要是字典序最小。

思路:先对点拓扑排序,因为要字典序最小,所以要将边全部反向,贪心从大往小编号,即大数能往后就往后。

# include <bits/stdc++.h>using namespace std;const int maxn = 1e5+3;int n, m, Next[maxn], in[maxn]={0}, ans[maxn],cnt=0;struct node{    int v, next;}edge[maxn<<1];void add_edge(int u, int v){    edge[cnt] = {v, Next[u]};    Next[u] = cnt++;}void solve(int sum){    priority_queue<int>q;    for(int i=1; i<=n; ++i)        if(in[i]==0)        {            --in[i];            q.push(i);        }    while(!q.empty())    {        int u = q.top();        q.pop();        ans[u] = sum--;        for(int i=Next[u]; i!=-1; i=edge[i].next)        {            int v = edge[i].v;            if(--in[v] == 0)                q.push(v);        }    }}int main(){    memset(Next, -1, sizeof(Next));    scanf("%d%d",&n,&m);    while(m--)    {        int a, b;        scanf("%d%d",&a,&b);        ++in[a];        add_edge(b, a);    }    solve(n);    for(int i=1; i<=n; ++i)        printf("%d%c",ans[i],i==n?'\n':' ');    return 0;}



原创粉丝点击