Codeforces 1159E 拓扑排序

Posted pkgunboat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 1159E 拓扑排序相关的知识,希望对你有一定的参考价值。

题意及思路:https://www.cnblogs.com/dd-bond/p/10859864.html

代码:

#include <bits/stdc++.h>
#define LL long long
#define db double
using namespace std;
const int maxn = 500010;
stack<pair<int ,int> >s;
vector<int> G[maxn];
int a[maxn], ans[maxn], tot, n;
void topsort(void) {
	queue<int> q;
	q.push(n + 1);
	while(!q.empty()) {
		int x = q.front();
		q.pop();
		for (int i = 0; i < G[x].size(); i++) {
			int y = G[x][i];
			ans[y] = tot--;
			q.push(y);
		}
	}
}
int main() {
	int T;
	scanf("%d", &T);
	while(T--) {
		scanf("%d", &n);
		tot = n;
		while(!s.empty())s.pop();
		for (int i = 1; i <= n + 1; i++) G[i].clear();
		bool flag = 0;
		for (int i = 1; i <= n; i++) {
			scanf("%d", &a[i]);
			if(a[i] == -1) a[i] = i + 1;
			while(!s.empty() && s.top().second <= i) s.pop();
			if(!s.empty() && a[i] > s.top().second) {
				flag = 1;
			} else {
				s.push(make_pair(i, a[i]));
				G[a[i]].push_back(i);
			}
		}
		if(flag) {
			printf("-1\\n");
		}
		else {
			topsort();
			for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
			printf("\\n");
		}
	}
	
}

  

以上是关于Codeforces 1159E 拓扑排序的主要内容,如果未能解决你的问题,请参考以下文章

codeforces 655D D. Robot Rapping Results Report(拓扑排序+拓扑序记录)

Codeforces915 D. Almost Acyclic Graph(思维,拓扑排序原理,拓扑排序判环)

CodeForces 909E Coprocessor(无脑拓扑排序)

Substring(Codeforces-D-拓扑排序)

CodeForces 129 BStudents and Shoelaces(拓扑排序)

Codeforces Round #290 (Div. 2) 拓扑排序