您的位置:首页 > 产品设计 > UI/UE

[POJ] Brackets Sequence

2015-06-22 17:58 453 查看
This problem can be solved elegantly using dynamic programming.

We maintain two arrays:

cnt[i][j] --- number of parentheses needed to add within s[i..j] inclusively;

pos[i][j] --- position to add the parenthesis within s[i..j] inclusively.

Then there are three cases:

cnt[i][i] = 1;

If s[i] == s[j], cnt[i][j] = cnt[i + 1][j - 1], pos[i][j] = -1 (no need to add any parenthesis);

If s[i] != s[j], cnt[i][j] = min_{k = i, i + 1, ..., j}cnt[i][k] + cnt[k + 1][j], pos[i][j] = k (choose the best position to add the parenthesis).

After computing cnt and pos, we will print the resulting parentheses recursively.

My accepted code is as follows. In fact, I spent a lot timg on debugging the Wrong Answer error due to incorrect input/output. You may try this problem at this link.

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;

#define INT_MAX 0x7fffffff
#define vec1d vector<int>
#define vec2d vector<vec1d >

void print(char* s, vec2d& pos, int head, int tail) {
if (head > tail) return;
if (head == tail) {
if (s[head] == '(' || s[head] == ')')
printf("()");
else printf("[]");
}
else if (pos[head][tail] == -1) {
printf("%c", s[head]);
print(s, pos, head + 1, tail - 1);
printf("%c", s[tail]);
}
else {
print(s, pos, head, pos[head][tail]);
print(s, pos, pos[head][tail] + 1, tail);
}
}

void solve(char* s, vec2d& cnt, vec2d& pos) {
int n = strlen(s);
for (int i = 0; i < n; i++)
cnt[i][i] = 1;
for (int l = 1; l < n; l++) {
for (int i = 0; i < n - l; i++) {
int j = i + l;
cnt[i][j] = INT_MAX;
if ((s[i] == '(' && s[j] == ')') || (s[i] == '[' && s[j] == ']')) {
cnt[i][j] = cnt[i + 1][j - 1];
pos[i][j] = -1;
}
for (int k = i; k < j; k++) {
if (cnt[i][k] + cnt[k + 1][j] < cnt[i][j]) {
cnt[i][j] = cnt[i][k] + cnt[k + 1][j];
pos[i][j] = k;
}
}
}
}
print(s, pos, 0, n - 1);
printf("\n");
}

int main(void) {
char s[110];
while (gets(s)) {
int n = strlen(s);
vec2d cnt(n, vec1d(n, 0));
vec2d pos(n, vec1d(n));
solve(s, cnt, pos);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: