码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 题目1141 Brackets Sequence(区间DP记录路径)

时间:2015-10-04 01:32:02      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

Brackets Sequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 27793   Accepted: 7885   Special Judge

Description

Let us define a regular brackets sequence in the following way:

1. Empty sequence is a regular sequence.
2. If S is a regular sequence, then (S) and [S] are both regular sequences.
3. If A and B are regular sequences, then AB is a regular sequence.

For example, all of the following sequences of characters are regular brackets sequences:

(), [], (()), ([]), ()[], ()[()]

And all of the following character sequences are not:

(, [, ), )(, ([)], ([(]

Some sequence of characters ‘(‘, ‘)‘, ‘[‘, and ‘]‘ is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.

Input

The input file contains at most 100 brackets (characters ‘(‘, ‘)‘, ‘[‘ and ‘]‘) that are situated on a single line without any other characters among them.

Output

Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.

Sample Input

([(]

Sample Output

()[()]

Source

ac代码
技术分享
#include<stdio.h>
#include<string.h>
char str[330];
int a[330][330],b[330],dp[330][330];
void print(int l,int r)
{
	if(l>=r)
		return;
	if(a[l][r]==-1)
	{
		print(l+1,r);
	}
		if(a[l][r]>0)
		{
			b[l]=1;
			b[a[l][r]]=1;
			print(l+1,a[l][r]-1);
			print(a[l][r],r);
		}
}
int main()
{
	while(gets(str+1))
	{
		int i,j,k;
		memset(dp,0,sizeof(dp));
		memset(a,-1,sizeof(a));
		memset(b,0,sizeof(b));
		int len=strlen(str+1);
		for(i=1;i<=len;i++)
		{
			dp[i][i]=1;
		}
		for(i=len-1;i>=1;i--)
		{
			for(j=i+1;j<=len;j++)
			{
				dp[i][j]=dp[i+1][j]+1;
				//a[i][j]=-1;
				for(k=i+1;k<=j;k++)
				{
					if((str[i]==‘(‘&&str[k]==‘)‘)||(str[i]==‘[‘&&str[k]==‘]‘))
					{
						if(dp[i][j]>dp[i+1][k-1]+dp[k][j]-1)
						{
							dp[i][j]=dp[i+1][k-1]+dp[k][j]-1;
							a[i][j]=k;
						//	b[i]=1;
						//	b[a[i][j]]=1;
						}
					}
				}
			}
		}
		print(1,len);
		for(i=1;i<=len;i++)
		{
			if(b[i]==1)
			{
				printf("%c",str[i]);
			}
			else
				if(str[i]==‘(‘||str[i]==‘)‘)
					printf("()");
				else
					printf("[]");
		}
		printf("\n");
	}
}

  

POJ 题目1141 Brackets Sequence(区间DP记录路径)

标签:

原文地址:http://www.cnblogs.com/Who-you/p/4854057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!