poj 1141 Brackets Sequence

题目链接:http://poj.org/problem?id=1141

题目大意:不解释。我的代码比较慢,主要是每次都合并字符串,也可以记录分割位置,最后确定输出。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
#include<stack>
#include<list>
#include<iostream>
#include<map>
using namespace std;
#define inf 0x3f3f3f3f
#define Max 110
int max(int a,int b)
{
	return a>b?a:b;
}
int min(int a,int b)
{
	return a<b?a:b;
}
int dp[Max][Max];
string str[Max][Max];
char s[Max];
int len;
int main()
{
    int i,j,k,l;
    scanf("%s",s);
    len=strlen(s);
    for(i=0;i<len;i++)
    {
        dp[i][i]=1;
        if(s[i]=='('||s[i]==')')
            str[i][i]="()";
        else
            str[i][i]="[]";
       // str[i][i][0]="()";
    }
    for(l=2;l<=len;l++)
        for(i=0;i<len&&i+l-1<len;i++)
        {
          //  printf("aa");
            j=i+l-1;
            dp[i][j]=inf;
            if(s[i]=='('&&s[j]==')')
            {
                if(len==2)
                {
                    dp[i][j]=1;
                    str[i][j]="()";
                }
                else
                {
                    dp[i][j]=dp[i+1][j-1]+1;
                    str[i][j]="(";
                    str[i][j]+=str[i+1][j-1];
                    str[i][j]+=")";
                }
            }
            if(s[i]=='['&&s[j]==']')
            {
                if(len==2)
                {
                    dp[i][j]=1;
                    str[i][j]="[]";
                }
                else
                {
                    dp[i][j]=dp[i+1][j-1]+1;
                    str[i][j]="[";
                    str[i][j]+=str[i+1][j-1];
                    str[i][j]+="]" ;
                }
            }
            for(k=i;k<j;k++)
            {
                if(dp[i][k]+dp[k+1][j]<dp[i][j])
                {
                    dp[i][j]=dp[i][k]+dp[k+1][j];
                    str[i][j]=str[i][k]+str[k+1][j];
                }
            }
          //  cout<<"i "<<i<<" j "<<j<<" "<<str[i][j]<<endl;
        }
        cout<<str[0][len-1]<<endl;
}


 

你可能感兴趣的:(String)