对一个有向无环图G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边<u,v>∈E(G),则u在线性序列中出现在v之前。
简单来说:有人想要制作一件工具,但是这个工具不是一次就可以完成的,分很多个步骤,而且这些步骤是有顺序的,也就是说,假设B的顺序在A的后面,那么你就必须要先完成A再完成B,但是也有些步骤不分顺序,意思是你先做哪一个都是可以的。
上图中,输出答案为afcdbe也是可以的
拓扑模板代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
vector <int> node[maxn];
vector <int> ans;
int n, m;
int in[maxn];
queue <int> q;
void tuopu() {
while(q.empty() == false) {
int x = q.front();
q.pop();
ans.push_back(x);
for(int i = 0; i < node[x].size(); i++) {
int y = node[x][i];
in[y]--;
if(in[y] == 0) q.push(y);
}
}
}
int main () {
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
node[x].push_back(y);
in[y]++;
}
for(int i = 1; i <= n; i++) {
if(in[i] == 0) q.push(i);
}
tuopu();
for(int i = 0; i < ans.size(); i++) cout << ans[i] << " ";
cout << endl;
}
/*
6 8
1 2
1 3
1 4
3 2
3 5
4 5
6 5
6 4
*/
借题解深入了解拓扑
UVA1423 Guess
#include <bits/stdc++.h>
using namespace std;
const int maxn = 205;
bool vis[maxn];
int head[maxn], in[maxn];
int cnt, num, n, t;
int a[maxn], sum[maxn];
string s;
struct Node {
int to, next;
}node[maxn];
void init() {
cnt = 0;
memset(vis, false, sizeof(vis));
memset(head, -1, sizeof(head));
memset(in, 0, sizeof(in));
for(int i = 0; i <= n; i++)
sum[i] = 10;
}
void add(int u, int v) {
in[v]++;
node[cnt].to = v;
node[cnt].next = head[u];
head[u] = cnt++;
}
void topu(int n) {
queue <int> q;
num = 0;
for(int i = 0; i <= n; i++) {
if((!in[i]) && (!vis[i])) {
q.push(i);
vis[i] = 1;
}
}
while(!q.empty()) {
int u = q.front();
q.pop();
for(int k = head[u]; k != -1; k = node[k].next) {
int y = node[k].to;
in[y]--;
sum[y] = sum[u] - 1;
if(!in[y]) {
q.push(y);
vis[y]=1;
}
}
}
//用下面的例子来说
//如果遍历到4,发现4有一条连着1的有向边,则sum[1] = sum[4] - 1;
//表示1到1小于1到4的前缀和
//证明:因为a[2]加到a[4]为正数,所以a[1]到a[4]的和减去a[1]为正数,即上面所说的1到1小于1到4的前缀和
}
int main() {
cin >> t;
while(t--) {
init();
memset(a, 0, sizeof(a));
cin >> n >> s;
int k = 0;
for(int i = 1; i <= n; i++)
for(int j = i; j <= n; j++) {
if(s[k] == '+') add(j, i - 1);
//为什么要减1?
//比如i = 2, j = 2时,代表a[i]为正数,则建一条2到1的有向边,而不能2和2建边
//又比如i = 2, j = 4时,代表从a[2]加到a[4]为正数,则建一条4到1的有向边
//又比如i = 2, j = 4时,如果从a[2]加到a[4]为负数,则建一条1到4的有向边
else if(s[k] == '-') add(i - 1, j);
k++;
}
topu(n);
for(int i = 1; i <= n; i++)
a[i] = sum[i] - sum[i - 1];
for(int i = 1; i < n; i++)
cout << a[i] << " ";
cout << a[n] << endl;
}
return 0;
}
/*
3
4
-+0++++--+
2
+++
5
++0+-+-+--+-+--
*/