拓扑排序:将一个有向无环图排序,使得所有排在前面的节点不能依赖于排在后面的节点
#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;
}