https://codeforces.com/contest/1413/problem/D
思路:正着去找的时候要先找到下面的-号再来确定上面的+的加号的内容而且连续的“-”的时候上面的要最小,有点类似栈。尝试倒着思考。
从后往前,当前stack为空的时候或者当前栈顶元素>要入栈的元素的时候,该操作是合法的,那么入栈。否则不合法。
当遇到+的时候,意味着有一个元素要踢掉了,把踢掉的这个元素记录下来。然后取出栈顶元素。
最后统一输出。
这样做的合法性:
倒序的时候就思考我们已经放好了所有足够的空摊位。就看当前空摊位怎么分配。
最后面进来的数要在其对应的区间内放。
比如
+
+
-2
-3
+
+
-1
-4
4要放在第4/3个+,1要放在4/3+,3放第1/2+,2放第1/2+。
也就是在取的数是合法的情况下,要放到能放得下的合法的摊位中。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e6+100;
typedef long long LL;
LL pre[maxn],cnt=0;
stack<LL>s;
struct P{
char op;
LL num;
}shu[maxn];
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL n;cin>>n;
for(LL i=1;i<=2*n;i++){
char str;LL num;
cin>>str;
if(str=='+'){
shu[i].op=str;
}
else if(str=='-'){
cin>>num;
shu[i].op=str;
shu[i].num=num;
}
}
for(LL i=2*n;i>=1;i--)
{
if(shu[i].op=='-'&&(!s.empty()&&s.top()>shu[i].num||s.empty())){
s.push(shu[i].num);
}
else if(shu[i].op=='+'){
if(!s.empty())
{
pre[++cnt]=s.top();
s.pop();
}
}
else {
cout<<"NO"<<endl;return 0;
}
}
if(!s.empty()){
cout<<"NO"<<endl;return 0;
}
cout<<"YES"<<endl;
for(LL i=cnt;i>=1;i--){
cout<<pre[i]<<" ";
}
cout<<endl;
return 0;
}