-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathQ10453.cpp
68 lines (61 loc) · 1.05 KB
/
Q10453.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <string.h>
int n,m;
char s[1010];
int dp[1010][1010],path[1010][1010];
int go(int i,int j) {
if(dp[i][j] != -1) return dp[i][j];
if(i >= j) return 0;
if(s[i] == s[j]) {
return (dp[i][j] = go(i+1,j-1));
} else {
int a,b;
a = go(i+1,j);
b = go(i,j-1);
if(a < b) {
dp[i][j] = a+1;
path[i][j] = 1;
} else {
dp[i][j] = b+1;
path[i][j] = 2;
}
return dp[i][j];
}
}
void print(int i,int j) {
if(i > j) return;
if(i == j) {
printf("%c",s[i]);
return;
}
if(s[i] == s[j]) {
printf("%c",s[i]);
print(i+1,j-1);
printf("%c",s[j]);
} else {
if(path[i][j] == 1) {
printf("%c",s[i]);
print(i+1,j);
printf("%c",s[i]);
} else {
printf("%c",s[j]);
print(i,j-1);
printf("%c",s[j]);
}
}
}
int main() {
int i,j,len;
while(gets(s) != NULL) {
n = strlen(s);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
dp[i][j] = -1;
path[i][j] = 0;
len = go(0,n-1);
printf("%d ",len);
print(0,n-1);
puts("");
}
return 0;
}