Topological order

Before I did not come across the topic of needed topological order, just know that thinking, did not realize before, met today to write about it. In fact, special topological order simple, do not need to feel ye speak.

 Topology order definition: a the DAG, all the vertices are arranged in a sequence, so that any one has to FIG side a-> b satisfy a occurs before b.

Ideas:

Before I will not come into contact with, that it really is not hard. QAQ   penetration of a point to illustrate this point 0 can be used as the first point of the current figure appeared, and then delete this point and all sides and the relevant point, the rest of the figure is once again looking into the degree 0 ,,, end point.

Can be considered the number of records of each of the points, first of all the point 0 into the queue, the first team takes out output, the adjacent edges of the first point minus one team, if after the completion of this operation Some of the dot becomes 0, and the team, the expanding degree of the current drawing point number 0 until the queue is empty can.

In particular, if the number of the final output point is less than the total number, indicating ring (the ring because each point has penetration, the absence of point 0).

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#define mem(a, b) memset(a, b, sizeof a)
using namespace std;
const int N = 310;
int cnt[N], head[N], nex[N], to[N], num;
void add(int a, int b){
	++num;
	to[num] = b;
	nex[num] = head[a];
	head[a] = num;
}
int n, m;
int main() {
	ios::sync_with_stdio(0);
	num = 0;
	mem(cnt, 0);
	mem(head, -1);
	mem(nex, -1);
	cin >> n >> m;
	cout << n << m << "\n";
	while (m--){
		int a, b;
		cin >> a >> b;
		add(a, b);
		cnt[b]++;
	}
	queue<int> q;
	for (int i = 1; i <= n; i++){
		if (!cnt[i])q.push(i);
	}
	while (!q.empty()){
		int t = q.front();
		cout << t << " ";
		q.pop();
		for (int i = head[t]; ~i; i = nex[i]){
			int y = to[i];
			cnt[y]--;
			if (!cnt[y]){
				q.push(y);
			}
		}
	}
	return 0;
}

 

Published 204 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43701790/article/details/104899217