Skip to content

Instantly share code, notes, and snippets.

@fredbr
Created May 3, 2018 05:52
Show Gist options
  • Save fredbr/55185bcfaf14ed7551053ea569ef3f02 to your computer and use it in GitHub Desktop.
Save fredbr/55185bcfaf14ed7551053ea569ef3f02 to your computer and use it in GitHub Desktop.
Palindrome
// solucao por Lucio Cardoso
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
string s;
cin >> n >> s;
int dp[2][n+1];
for (int i = n; i >= 1; i--)
{
for (int j = i; j <= n; j++)
{
if (i == j)
dp[i%2][j] = 1;
else if (j == i+1)
{
if (s[i-1] == s[j-1]) dp[i%2][j] = 2;
else dp[i%2][j] = 1;
}
else
{
if (s[i-1] == s[j-1]) dp[i%2][j] = 2+dp[(i+1)%2][j-1];
else dp[i%2][j] = max(dp[(i+1)%2][j], dp[i%2][j-1]);
}
}
}
cout << n-dp[1][n] << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment