ACM PKU 1141 Brackets Sequence http://acm.pku.edu.cn/JudgeOnline/problem?id=1141

这家伙磨了我几天了,解题报告稍后上:

#include <iostream>
#include <string>
using namespace std;

const int Max = 999999;

int flag[202][202],sign[202][202];
char str[202];

inline int min (int a,int b)
{
return a > b ? b : a ;
}

int Find_Match(int len)
{
memset(flag,0,sizeof(flag));

int i, j, k, m;

for (i = len; i > 0 ; i--)
{ 
   str[i] = str[i-1];
   flag[i][i] = 1;
}

for (k = 1 ; k <= len ; k++)
   for (i = 1;i <= len-k; i++)
   {
    j = i + k;
    flag[i][j] = Max ;

    if ((str[i]=='(' && str[j]==')')||(str[i]=='[' && str[j]==']'))
     flag[i][j] = min(flag[i][j],flag[i+1][j-1]);
     sign[i][j] = -1 ;

    for (m = i ;m < j; m++)
    {
     if (flag[i][j] > flag[i][m]+flag[m+1][j])
     sign[i][j] = m ;
     flag[i][j] = min(flag[i][j],flag[i][m]+flag[m+1][j]);
      
    }
   }

   // cout<<flag[1][len]<<endl;

   return flag[1][len];

}

void output(int s,int e)
{
if (s > e) return ;
if (s == e)
{
   if (str[s] == '(' || str[s] == ')')
    cout<<"()";
   else 
    cout<<"[]";
}
else 
{
   if (sign[s][e] == -1)
   {
    if (str[s]=='(')
    {
     cout<<'(';
     output(s+1,e-1);
     cout<<')';
    }
    else 
    {
     cout<<'[';
     output(s+1,e-1);
     cout<<']';
    
    }
   }
   else
   {
    output(s,sign[s][e]);
    output(sign[s][e]+1,e);
   }
}
}

int main ()
{
    gets(str);
int len = strlen(str);

Find_Match(len);

output(1,len);
cout<<endl;
return 0;
}

posted on 2011-05-06 18:44  _Clarence  阅读(84)  评论(0编辑  收藏

导航

统计