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.
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.
Print n numbers — lexicographically smallest correct permutation of labels of vertices.
3 3 1 2 1 3 3 2
1 3 2
4 5 3 1 4 1 2 3 3 4 2 4
4 1 2 3
5 4 3 1 2 1 2 3 4 5
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;
}