fork(2) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string str; // input string
  5. string rev; // reverse of the input string
  6. int dp[50][50]; // LCS 2-d array
  7.  
  8. // return length of LCS between string a and string b
  9. int LCS(string a, string b)
  10. {
  11. memset(dp, 0, sizeof dp);
  12. int a_len = a.length();
  13. int b_len = b.length();
  14.  
  15. for(int i=1; i<=a_len; i++){
  16. for(int j=1; j<=b_len; j++){
  17. if(a[i-1]==b[j-1]){
  18. dp[i][j] = dp[i-1][j-1] + 1;
  19. }
  20. else{
  21. dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
  22. }
  23. }
  24. }
  25.  
  26. return dp[a_len][b_len];
  27. }
  28.  
  29. void solve()
  30. {
  31. cin>>str;
  32. rev = str;
  33. reverse(rev.begin(), rev.end());
  34. int lcs = LCS(str, rev);
  35. cout<< str.length() - lcs <<endl;
  36. }
  37.  
  38. int main()
  39. {
  40. ios_base::sync_with_stdio(0);
  41.  
  42. int t=1; cin>>t;
  43. while(t--){
  44. solve();
  45. }
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 15248KB
stdin
4
anasdad
abcd
aba
geeks
stdout
4
3
0
3