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

时间:2024-09-26 20:37:32

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

http://blog.****.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 = + ; int n,m; int dp[][],path[][];
char a[]; 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] == -)
{
pf("%c",a[i]);
print(i+,j-);
pf("%c",a[j]);
return;
}
else
{
print(i,path[i][j]);
print(path[i][j]+,j);
}
} int main()
{
int i,j;
while(gets(a))
{
n = strlen(a);
mem(dp,);
mem(path,);
for(i=;i<n;i++)
dp[i][i]=;
for(int l = ;l<n;l++)
{
for(i=;i<n-l;i++)
{
j = i+l;
dp[i][j] = <<;
if(match(i,j) && dp[i+][j-] < dp[i][j])
{
dp[i][j] = dp[i+][j-];
path[i][j] = -;
} for(int k =i;k<j;k++)
{
if(dp[i][k]+dp[k+][j] < dp[i][j])
{
dp[i][j] = dp[i][k]+dp[k+][j];
path[i][j] = k;
}
}
}
}
print(,n-);
blank;
}
return ;
}