Shurikens(思维+倒序栈模拟)

52 篇文章 1 订阅

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;
}

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值