拓扑排序简介及其应用

拓扑排序是数据结构图论中的一点内容。
拓扑排序主要用来解决有向图中的依赖解析(dependency resolution)问题。
这里主要写几个模板~~~~
题目链接(http://acm.hdu.edu.cn/showproblem.php?pid=1285)

#include
#include
using namespace std;
const int M = 505;
int raod[M][M], p[M];
int ans[M];
//void init() {
//	memset(p, 0, sizeof(0));
//	memset(ans, 0, sizeof(ans));
//	memset(raod, 0, sizeof(raod));
//}
int main() {
	int n, m, x, y;
	while (cin >>n>>m){
		for (int i = 1; i <= n; i++)
			p[i] = 0, ans[i] = 0;
		for (int i = 0; i <= n; i++)
			for (int j = 0; j <= n; j++)
				raod[i][j] = 0;
		for (int i = 0; i < m; i++)
			cin >> x >> y, raod[x][y] = 1;
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				if (raod[i][j])
					p[j]++;
		for (int i = 1; i <= n; i++)
		{
			int k = 1;
			while (p[k] != 0) {
				k++;
			}
			ans[i] = k;
			p[k] = -1;
			for (int j = 1; j <= n; j++) {
				if (raod[k][j])
					p[j]--;
			}
		}
		for (int i = 1; i <= n; i++)
		{
			if (i < n)
				cout << ans[i] << " ";
			else
				cout << ans[i] << endl;


		}
	}
	return  0;
}

这样写数据量一大就容易超时。
题目链接(http://acm.hdu.edu.cn/showproblem.php?pid=5695)

#include

#include

#include
using namespace std;
const int M = 100010;
vector<int>v[M];
int p[M];
int  answer[M];
int n, m;
int cont ;
void toposort(){
	 cont = 0;
	 priority_queue<int>que;
	for (int i = n; i > 0; i--)
		if (!p[i])que.push(i);
	while (!que.empty()) {
		int tem = que.top();
		que.pop();
		answer[cont++] = tem;
		for (int i = 0; i < int(v[tem].size()); i++) {
			p[v[tem][i]]--;
			if (p[v[tem][i]] == 0)que.push(v[tem][i]);
		}

	}
}
int main() {
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> m;
		int a, b;
		for (int i = 0; i <= n; i++)
			v[i].clear(), p[i] = 0;
		for (int i = 0; i < m; i++)
		{
			scanf("%d%d", &a, &b);
			p[b]++;
			v[a].push_back(b);
		}
		toposort();
		long long min = 1000000000;
		long long sum = 0;
		for (int i = 0; i < cont; i++)
		{
			min = min > answer[i] ? answer[i] : min;
			sum += min;
		}
		printf("%lld\n", sum);

	}
	return 0;
}

利用优先队列和vector来实现拓扑排序相对来说就快了很多。

你可能感兴趣的:(拓扑排序简介及其应用)