-
Notifications
You must be signed in to change notification settings - Fork 0
/
137D.rb
76 lines (70 loc) · 1.04 KB
/
137D.rb
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
69
70
71
72
73
74
75
76
$s=gets.split[0]
$n=$s.length
$k=gets.split[0].to_i
dp=Array.new($n+1){Array.new($n+1,0)}
def solve(s,e)
e-=1
str=$s[s..e]
ans=0
0.upto(str.length-1){|i|
if str[i]!=str[str.length-1-i] then
ans+=1
end
}
ans/2
end
def solve2(s,e)
e-=1
str=$s[s..e]
ans=0
0.upto(str.length-1){|i|
if str[i]!=str[str.length-1-i] then
str[i]=str[str.length-1-i]
end
}
str
end
0.upto($n-1){|i|
(i+1).upto($n){|j|
dp[i][j]=solve(i,j)
}
}
memo=Array.new($k+2){Array.new($n+2,9999999)}
memo[0][0]=0
back=Array.new($k+2){Array.new($n+2,9999999)}
0.upto($k){|j|
0.upto($n-1){|i|
(i+1).upto($n){|k|
if memo[j+1][k]>memo[j][i]+dp[i][k] then
memo[j+1][k]=memo[j][i]+dp[i][k]
back[j+1][k]=i
end
}
}
}
ans=999999999
for i in 1..$k
ans=[ans,memo[i][$n]].min
end
p ans
tar=0
for i in 1..$k
if ans==memo[i][$n] then tar=i end
end
i=tar
j=$n
res=[]
loop do
res.push([back[i][j],j])
j=back[i][j]
i-=1
if i==0 then
break
end
end
res.reverse!
0.upto(res.size-1){|i|
if i>0 then print "+" end
print solve2(res[i][0],res[i][1])
}
puts ""