codeforces 1435 D. Shurikens (贪心)

题目链接:https://codeforces.com/contest/1435/problem/D

考虑维护一个栈,对于每一个封闭的栈,出栈的\(cost\)的顺序必须是递增的,否则必然不满足条件
那么就维护与当前元素\(i\)形成封闭栈的元素的位置\(pos[i]\),\(a_i\)就是第 \(pos[i]\) 个进栈的元素
最后检查一下是否每个封闭栈中元素大小都单调即可

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 200100;

int n,cnt;
int a[maxn],pos[maxn],op[maxn],ans[maxn];
int sta[maxn],tail = 0;

char s[10];

priority_queue<int,vector<int>,greater<int> > q;

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read();
	int x; int cnt = 0; int tot = 0; int flag = 0;
	for(int i=1;i<=2 * n;++i){
		scanf("%s",s);
		if(s[0]=='+'){
			op[i] = 0;
			sta[++tail] = ++cnt;
		}else{
			op[i] = 1;
			if(!tail){
				flag = 1;
				break;
			}
			a[++tot] = read();
			pos[tot] = sta[tail--];
		}
	}
	
	if(!flag){
		cnt = 0; tot = 0;
		for(int i=1;i<=n;++i) ans[pos[i]] = a[i];
		for(int i=1;i<=2 * n;++i){
			if(!op[i]){
				q.push(ans[++cnt]);
			}else{
				if(a[++tot] != q.top()){
					flag = 1;
					break;
				}else{
					q.pop();
				}
			}
		}
	}
	
	if(flag){
		printf("NO\n");
	}else{
		printf("YES\n");
		for(int i=1;i<=n;++i){
			printf("%d ",ans[i]);
		}printf("\n");
	}
	

	return 0;
}
posted @ 2020-10-25 23:55  Tartarus_li  阅读(343)  评论(0编辑  收藏  举报