CF825E: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条边的有向图,要你为这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;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值