Original question:
E. Minimal Labels
Time limit per test1 second
Memory limit per test256 megabytes
Inputstandard input
Outputstandard output
You is given a directed acyclic graph with n vertices and m edges. There is 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-to-that:
Labels form a valid permutation of length N-an integer sequence such that all integer from 1 to n appears exactly once In it.
If there exists an edge from vertex v to vertex u then Labelv should is smaller than labelu.
Permutation should is lexicographically smallest among all suitable.
Find such sequence of labels to satisfy all the conditions.
Input
The first line contains the numbers n, m (2≤n≤105, 1≤m≤105).
Next m lines contain-numbers v and U (1≤v, u≤n, V≠u)-edges of the graph. Edges is 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
English:
Give you a directed loop graph that lets you label each node, and the node being pointed to is smaller than the node that points to it. The label order of the output dictionary order is minimal.
#include <bits/stdc++.h> using namespace std;
int n, m;
int deg[100001];
Vector<int> gra[100001];
int ans[100001];
void Topsort () {memset (ans, 0, sizeof (ans));
Priority_queue<int, Vector<int>, less<int> > Q;
int cnt = n;
for (int i = 1; I <= n; i++) if (deg[i] = = 0) {Q.push (i);
} while (!q.empty ()) {int h = q.top ();
Q.pop ();
ANS[H] = cnt--;
if (gra[h].size () = = 0) continue;
for (int i=0;i<gra[h].size (); i++) {if (--deg[gra[h][i]]==0) Q.push (Gra[h][i]);
}}} int main () {Ios::sync_with_stdio (false);
while (CIN >> n >> m) {memset (GRA, 0, sizeof (GRA));
memset (deg, 0, sizeof (deg));
for (int i = 1; I <= n; i++) gra[i].clear ();
for (int i = 0; i<m; i++) {int A, B; Cin >> a >>
b
Gra[b].push_back (a);
deg[a]++;
} topsort ();
for (int i = 1; I <= n; i++) if (i! = N) cout << ans[i] << "";
else cout << Ans[i] << Endl;
} return 0;
}
Answer:
First of all, the topic can be learned that the degree of 0 of the nodes are taken out, according to the dictionary order, and then the node out of all the edges removed. Repeat the process above. This is the process of topological sequencing.
CF on the e question incredibly is bare topological sort, I get a leng.
But the problem is also a little bit curved.
Using the queue topology sorting algorithm to use the priority queue, and secondly, to find the reverse, that is, each time the maximum degree of penetration, the largest element must be ranked in the last side.