CF508E

2 篇文章 0 订阅
1 篇文章 0 订阅

贪心题是很有趣的...

首先,本题为括号匹配问题,那么可以考虑进行栈模拟

然后,我们思考一下如何匹配:虽然题目中仅对右括号的位置提出了区域性要求,但可以发现,对能匹配上的栈顶括号立刻进行匹配一定是一种最优解!

为什么?

根据括号匹配原则,如果栈顶括号未被匹配,那么其他括号将无法被匹配,那么栈顶括号越长时间不被匹配,栈内括号失配的可能就越大。相反,如果我们对能匹配的栈顶括号立刻进行匹配,不会存在反例使得本能匹配上的其他括号未能被匹配。

所以这题的剩余部分就变成了一个模拟...

#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
int l[605],r[605];
int n;
int my_stack[605];
int posi[605];
int ttop=0;
int typ[1205];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d",&l[i],&r[i]);
	}
	int pos=2;
	int cnt=1;
	typ[1]=1;
	my_stack[++ttop]=1;
	posi[ttop]=1;
	while(pos<=2*n)
	{
		int t=my_stack[ttop];
		int p=posi[ttop];
		if(p+l[t]<=pos&&p+r[t]>=pos)
		{
			typ[pos]=2;
			ttop--;
			pos++;
		}else
		{
			my_stack[++ttop]=++cnt;
			posi[ttop]=pos;
			typ[pos]=1;
			pos++;
		}
	}
	if(ttop)
	{
		printf("IMPOSSIBLE\n");
		return 0;
	}else
	{
		for(int i=1;i<=2*n;i++)
		{
			if(typ[i]==1)
			{
				printf("(");
			}else
			{
				printf(")");
			}
		}
		printf("\n");
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值