@LIUHUAN
2020-01-19T13:28:16.000000Z
字数 927
阅读 588
algorithm
// 是否是回文的判断
int isPaline(string& s, int i, int j)
{
int r = 1;
while (i < j) {
if (s[i] == s[j]) {
i++;
j--;
} else {
r = 0;
break;
}
}
return r;
}
int mincut(string s)
{
int n = s.size();
vector<vector<int>> pl(n, vector<int>(n, 0));
vector<vector<int>> dp(n, vector<int>(n, n));
for (int i = 0; i < n; i++) {
pl[i][i] = 1;
dp[i][i] = 0;
}
// 计算回文字符串
for (int l = 1; l < n; l++) {
for (int i = 0; i < n - l; i++) {
int j = i + l;
pl[i][j] = isPaline(s, i, j);
}
}
// 计算最小切割数
for (int l = 1; l < n; l++) {
for (int i = 0; i < n - l; i++) {
int j = i + l;
if (pl[i][j] == 1) {
dp[i][j] = 0;
continue;
}
for (int k = i; k < j; k++) {
int cut_cost = dp[i][k] + dp[k + 1][j] + 1;
dp[i][j] = min(dp[i][j], cut_cost);
}
}
}
return dp[0][n - 1];
}
int main()
{
string s("helloworld");
cin >> s;
int r = mincut(s);
cout << s << endl;
cout << s.size() << endl;
cout << r << endl;
}