Iamtui1010

sym.cpp

Jan 15th, 2022
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4. #include<algorithm>
  5.  
  6. #define long long long
  7. #define nln '\n'
  8.  
  9. const long N = 1e3;
  10.  
  11. using namespace std;
  12.  
  13. fstream f1, f2;
  14.  
  15. inline void openf()
  16. {
  17.     f1.open("sym.inp", ios:: in);
  18.     f2.open("sym.out", ios:: out);
  19. }
  20.  
  21. inline void closef()
  22. {
  23.     f1.close();
  24.     f2.close();
  25. }
  26.  
  27. string str;
  28.  
  29. void data()
  30. {
  31.     f1.tie(0)->sync_with_stdio(0);
  32.     f2.tie(0)->sync_with_stdio(0);
  33. }
  34.  
  35. string palindrome(string str)
  36. {
  37.     // Dynamic planning
  38.     long n = str.size();
  39.     vector<vector<long>> dp(N);
  40.     for (long i = 0; i <= n; ++i)
  41.         dp[i].resize(n+2, 0);
  42.  
  43.     for (long i = 1; i <= n; ++i)
  44.         for (long j = 0; j < n-i+1; ++j)
  45.         {
  46.             long lef = j, rig = j+i-1;
  47.  
  48.             if (rig == lef)
  49.             {
  50.                 dp[lef][rig] = 0;
  51.                 continue;
  52.             }
  53.  
  54.             if (rig - lef == 1)
  55.             {
  56.                 if (str[lef] != str[rig])
  57.                     dp[lef][rig] = 1;
  58.                 continue;
  59.             }
  60.  
  61.             if (str[lef] == str[rig])
  62.             {
  63.                 dp[lef][rig] = dp[lef+1][rig-1];
  64.                 continue;
  65.             }
  66.             dp[lef][rig] = min(dp[lef][rig-1], dp[lef+1][rig])+1;
  67.         }
  68.  
  69.     // Trace
  70.     long lef = 0, rig = n-1, add = 0;
  71.     while (lef < rig)
  72.     {
  73.         if (str[lef] == str[rig])
  74.         {
  75.             ++lef; --rig;
  76.             continue;
  77.         }
  78.  
  79.         if (dp[lef-add][rig] == dp[lef+1-add][rig]+1)
  80.         {
  81.             str.insert(str.begin()+rig+1, str[lef]);
  82.             ++lef;
  83.         }
  84.         else
  85.         {
  86.             str.insert(str.begin()+lef, str[rig]);
  87.             ++lef;
  88.             ++add;
  89.         }
  90.     }
  91.     return str;
  92. }
  93.  
  94. void process()
  95. {
  96.     long T;
  97.     f1 >> T;
  98.     for (long t = 1; t <= T; ++t)
  99.     {
  100.         f1.ignore();
  101.         getline(f1, str, nln);
  102.         f2 << palindrome(str) << nln;
  103.     }
  104. }
  105.  
  106. void view()
  107. {
  108.  
  109. }
  110.  
  111.  
  112. int main()
  113. {
  114.     openf();
  115.     data();
  116.     process();
  117.     view();
  118.     closef();
  119.     return 0;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment