码迷,mamicode.com
首页 > 编程语言 > 详细

Codeforces 1159E 拓扑排序

时间:2019-05-18 00:37:07      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:思路   tps   code   .com   bond   flag   back   push   clear   

题意及思路: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 拓扑排序

标签:思路   tps   code   .com   bond   flag   back   push   clear   

原文地址:https://www.cnblogs.com/pkgunboat/p/10884218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!