POJ 1141 Brackets Sequence
来源:互联网 发布:数据库实例 编辑:程序博客网 时间:2024/03/29 18:56
Description
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
Output
Sample Input
([(]
Sample Output
()[()]
Source
/*
http://acm.pku.edu.cn/JudgeOnline/problem?id=1141
动态规划,与最优二叉查找树类似,从下往上,从小到大,遍历长度len,然后遍历位置k
*/
#include <iostream>
#define MAX_N 100
using namespace std;
char input[MAX_N + 1];
int len;
int pos[MAX_N + 1][MAX_N + 1];
int minV[MAX_N + 1][MAX_N + 1];
void print(int f, int t)
{
if(f > t)
return;
if(pos[f][t] == -1)
{
cout<<input[f];
print(f + 1, t - 1);
cout<<input[t];
}
else if(f == t)
{
char type = input[f];
if(type == ')' || type == '(')
cout<<"()";
else
cout<<"[]";
}
else
{
print(f, pos[f][t]);
print(pos[f][t] + 1, t);
}
}
bool match(char t1, char t2)
{
return ((t1 == '(' && t2 == ')') || (t1 == '[' && t2 == ']'));
}
int main()
{
char ch;
len = 0;
while((ch = getchar()) != 10)
{
input[++len] = ch;
}
int i, j;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(i == j)
minV[i][j] = 1;
}
}
int l, k;
for(l = 2; l <= len; l++)
{
for(i = 1; i <= len - l + 1; i++)
{
j = i + l - 1;
int minVal = INT_MAX, minPos = 0, curVal;
for(k = i; k < j; k++)
{
curVal = minV[i][k] + minV[k + 1][j];
if(curVal < minVal)
{
minVal = curVal;
minPos = k;
}
}
if(match(input[i], input[j]))
{
curVal = minV[i + 1][j - 1];
if(curVal < minVal)
{
minVal = curVal;
minPos = -1; //min trim head and tail
}
}
minV[i][j] = minVal;
pos[i][j] = minPos;
}
}
print(1, len);
cout<<endl;
return 0;
}
- POJ 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- Brackets Sequence--poj--1141
- poj 1141 Brackets Sequence
- poj 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- poj 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- poj 1141(Brackets Sequence)
- poj 1141 brackets sequence
- poj 1141 Brackets Sequence
- POJ 1141 Brackets Sequence
- poj 1141 Brackets Sequence
- poj 1141 brackets sequence
- POJ-1141-Brackets Sequence
- POJ - 1141 Brackets Sequence
- 深入浅出vector之resize()/reserve(), size()/capacity()
- MagicAjax使用手册
- 自举
- 修改sql server 的连接数
- Linux脚本编写基础
- POJ 1141 Brackets Sequence
- 如何将Java工程导出为Jar包
- Linux文件搜索之 find / locate / whereis / which
- V4L2官方实例
- 十一了,回家喽
- DSP的自举引导方法的应用研究
- CCR 环境下移动存储组
- 困扰几天的webservices异常.终于解决!
- Python中SQLite数据库使用初步