zoj 2704 Brackets

输出最长的配对序列,brackets—括号可怜

忘了当时怎么讨论的了,总之用栈来存储

序列的对应的标号,标号差值与序列的

度相关,然后从small 到big输出,只知道

当时很纠结可怜

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#include<math.h>



#define maxn 100000



char target[maxn+10];

int stack[maxn+10];



int top;                         //栈顶的元素的下标 



void push(int x)                 //入栈 

{

   stack[top] = x;

}



void pop()                       //出栈 

{

   stack[top] = 0;

}



int match(int m,int n)           //检查是否匹配 

{

    if(target[ stack[m] ] == '(' && target[n] == ')')

        return 1;

    if(target[ stack[m] ] == '[' && target[n] == ']')

        return 1;

    else 

      return 0;

}





int main()

{

     int i,len,max,big,small;

     

    

     while(scanf("%s",target)==1)

     {

	 len = strlen(target);

	 top = 0;

	 push(len);                   //栈底元素,判断栈是否为空

	 top = 1;

         push(0);                   //target的首号元素下标 

         for(i=1;i<len;i++)

	 {

	    if(match(top,i))

	    {

		pop();

		top--;

	    }

	    else

	    {

		top++;

		push(i);

	    }

         }

	  if(top == 0)

	     printf("%s\n\n",target);

	  else if(top == len)

	     printf("\n\n");

	  else if(top>0&&top<len)

	  {

             stack[0] = -1;

             max = 0;

             big = 0;

             small = 0;

             int m;

             stack[top+1] = len;

             for(i=1;i<=top+1;i++)

             {

		if((m = stack[i] - stack[i-1]) > max)

		{

		    max = m;

		    big = stack[i];

		    small = stack[i-1];

		}

	     }

	     for(i=small+1;i<big;i++)

	       printf("%c",target[i]); 

	     printf("\n\n");

	  }

	  

     } 

     return 0;

}


 

你可能感兴趣的:(rack)