zoukankan      html  css  js  c++  java
  • Codeforce612C

    You are given string s consists of opening and closing brackets of four kinds <>,{}[](). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.

    The following definition of a regular bracket sequence is well-known, so you can be familiar with it.

    Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2{s1}s2[s1]s2(s1)s2 are also RBS.

    For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.

    Determine the least number of replaces to make the string s RBS.

    Input

    The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

    Output

    If it's impossible to get RBS from s print Impossible.

    Otherwise print the least number of replaces needed to get RBS from s.

    Example
    Input
    [<}){}
    
    Output
    2
    Input
    {()}[]
    
    Output
    0
    Input
    ]]
    
    Output
    Impossible

    题目大意:给出一个括号序列,要求替换若干括号使原括号变成正则括号序列(即合法的匹配序列)。替换只能将左括号替换成不同类型的左括号,右括号替换成不同类型的右括号。问最少的替换个数,如果不存在这样的替换则输出 Impossible

    题解:先打表,把情况列出来,然后用数组模拟栈操作

    AC代码为:


    #include<stdio.h>
    #include<string.h>
    #include<stdbool.h>
    #define max 1000005
    
    int top=0;
    char str[max];
    
    int judge(char s1,char s2)
    {
    	if(s1=='[' && s2==']')
    		return 1;
    	else if(s1=='{' && s2=='}')
    		return 1;
    	else if(s1=='(' && s2==')')
    		return 1;
    	else if(s1=='<' && s2=='>')
    		return 1;
    	else if((s1=='<'||s1=='['||s1=='{'||s1=='(')&&(s2=='>'||s2==']'||s2=='}'||s2==')')) 
    		return 2;
    	else
    		return 0;
    }
    
    int main()
    {
    	char ch;
    	int num=0;
    	scanf("%c",&ch);
    	str[top++]=ch;
    	while(scanf("%c",&ch)!=EOF && ch!='
    ')		
    	{
    		str[top++]=ch;
    		if(judge(str[top-2],str[top-1])==1)
    		{
    			top-=2;
    		}
    		else if(judge(str[top-2],str[top-1])==2)
    		{
    			top-=2;
    			num++;
    		}	
    	}
    	if(top)
    		printf("Impossible
    ");
    	else
    		printf("%d
    ",num);
    		return 0;
    	
    } 

  • 相关阅读:
    题解:[HNOI2004]树的计数
    题解:砝码称重
    题解:子矩阵(NOIP2014普及组T4)
    题解:低价购买
    题解:倍增三连击orz
    题解:UVA10140 Prime Distance
    题解:[JSOI2007]建筑抢修
    模板:三分法
    Databinging数据绑定
    开始
  • 原文地址:https://www.cnblogs.com/csushl/p/9386633.html
Copyright © 2011-2022 走看看