拓扑排序(uva1423)

拓扑排序:将一个有向无环图排序,使得所有排在前面的节点不能依赖于排在后面的节点

#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 12;
string str;
int n,inDegrees[maxn],sum[maxn];
vector<int> m[maxn];

void TopoSort()
{
	queue<int> q;
	for (int i = 0; i <= n; i++) {
		if (inDegrees[i] == 0) q.push(i);
	}

	int value = 0;
	while (!q.empty()) {
		int len = q.size();
		for (int i = 0; i < len; i++) {
			int top = q.front(); q.pop();
			sum[top] = value;
			for (int j = 0; j < m[top].size(); j++) {
				int nx = m[top][j];
				if (--inDegrees[nx] == 0) {
					q.push(nx);
				}
			}
		}
		value++;
	}
}
int main()
{
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> str;
		memset(inDegrees, 0, sizeof(inDegrees));
		memset(sum, 0, sizeof(sum));
		for (int i = 0; i <= n; i++) m[i].clear();

		int index = 0;
		for (int i = 1; i <= n; i++) {
			for (int j = i; j <= n; j++) {
				char ch = str[index++];
				if (ch == '+') {
					//B[j] > B[i - 1]
					m[i - 1].push_back(j);
					inDegrees[j]++;
				}
				else if (ch == '-') {
					//B[j] < B[i - 1]
					m[j].push_back(i - 1);
					inDegrees[i - 1]++;
				}
			}
		}
		TopoSort();
		for (int i = 1; i < n; i++) {
			cout << sum[i] - sum[i - 1] << " ";
		}
		cout << sum[n] - sum[n - 1] << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值