poj 1141 Brackets Sequence ( 区间dp+输出方案 )

http://blog.csdn.net/cc_again/article/details/10169643

http://blog.csdn.net/lijiecsu/article/details/7589877

如果有空串要用gets,scanf不能处理空串

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <cctype>
#include <vector>
#include <iterator>
#include <set>
#include <map>
#include <sstream>
using namespace std;

#define mem(a,b) memset(a,b,sizeof(a))
#define pf printf
#define sf scanf
#define spf sprintf
#define pb push_back
#define debug printf("!\n")
#define INF 10000
#define MAX(a,b) a>b?a:b
#define blank pf("\n")
#define LL long long
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pqueue priority_queue

const int MAXN = 1000 + 5;

int n,m;

int dp[110][110],path[110][110];
char a[110];

bool match(int i,int j)
{
    return (a[i]=='(' && a[j]== ')') || (a[i]=='[' && a[j]== ']');
}
void print(int i,int j)
{
    if(i>j) return;
    if(i == j)
    {
        if(a[i] == '(' || a[i]== ')')
            pf("()");
        else
            pf("[]");
        return;
    }
    if(path[i][j] == -1)
    {
        pf("%c",a[i]);
        print(i+1,j-1);
        pf("%c",a[j]);
        return;
    }
    else
    {
        print(i,path[i][j]);
        print(path[i][j]+1,j);
    }
}

int main()
{
    int i,j;
    while(gets(a))
    {
        n = strlen(a);
        mem(dp,0);
        mem(path,0);
        for(i=0;i<n;i++)
            dp[i][i]=1;
        for(int l = 1;l<n;l++)
        {
            for(i=0;i<n-l;i++)
            {
                j = i+l;
                dp[i][j] = 1<<30;
                if(match(i,j) && dp[i+1][j-1] < dp[i][j])
                {
                    dp[i][j] = dp[i+1][j-1];
                    path[i][j] = -1;
                }

                for(int 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];
                        path[i][j] = k;
                    }
                }
            }
        }
        print(0,n-1);
        blank;
    }
    return 0;
}

 

posted @ 2016-05-06 12:56  qlky  阅读(174)  评论(0编辑  收藏  举报