zoukankan      html  css  js  c++  java
  • CF508E

    贪心题是很有趣的...

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

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

    为什么?

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

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

    #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
    ");
    		return 0;
    	}else
    	{
    		for(int i=1;i<=2*n;i++)
    		{
    			if(typ[i]==1)
    			{
    				printf("(");
    			}else
    			{
    				printf(")");
    			}
    		}
    		printf("
    ");
    	}
    	return 0;
    }
  • 相关阅读:
    AJAX入门之深入理解JavaScript中的函数
    檔案下載function
    数据库的分页问题
    如何手动删除归档日志
    ORA00257 archiver error. 错误的处理方法
    关于Change Data Capture(六)查询CDC信息
    Cognos 的技巧
    Structs工作原理
    strutsconfig.xml属性含义
    Oracle性能查询统计信息的SQL语句
  • 原文地址:https://www.cnblogs.com/zhangleo/p/10764175.html
Copyright © 2011-2022 走看看