AhmedAshraff

Untitled

Sep 21st, 2025
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define boAshraf ios_base::sync_with_stdio(false); cin.tie(NULL);
  4. #define ll long long
  5. #define sz(s) (int)(s).size()
  6. #define all(s) (s).begin(),(s).end()
  7. using namespace std;
  8.  
  9. void File();
  10. void sol();
  11. const int N=5001;
  12. string s;
  13. int n;
  14. int common[N][N];
  15. int dp[N][N];
  16. int get(int i,int j){
  17.     if(j==n)return 0;
  18.     int &ret=common[i][j];
  19.     if(~ret)return ret;
  20.     ret=0;
  21.     if(s[i]==s[j])ret=1+get(i+1,j+1);
  22.     return ret;
  23. }
  24. int rec(int i,int last){
  25.     if(i>n)return -1e9;
  26.     if(i==n)return 0;
  27.     int &ret=dp[i][last];
  28.     if(~ret)return ret;
  29.     ret=-1e9;
  30.     if(last!=0) {
  31.         ret = max(ret, rec(i + 1, last + 1));
  32.         int c=min(last+1,get(i-last,i));
  33.         int i1=i-last+c,i2=i+c;
  34.         if(c>=last)ret=max(ret,1+rec(i+last+1,last+1));
  35.         else if(s[i1]<s[i2])ret=max(ret,1+rec(i+c+1,c+1));
  36.     }else{
  37.         ret=rec(i+1,1)+1;
  38.     }
  39.     return ret;
  40. }
  41. void build(int i,int last){
  42.     if(i==n) {
  43.         cout<<s.substr(i-last,last)<<'\n';
  44.         return;
  45.     }
  46.     int &ret=dp[i][last];
  47.     if(last!=0) {
  48.         if(ret==rec(i+1,last+1)){
  49.             return build(i+1,last+1);
  50.         }
  51.         int c=min(last+1,get(i-last,i));
  52.         int i1=i-last+c,i2=i+c;
  53.         if(c>=last && ret==1+rec(i+last+1,last+1)) {
  54.             cout<<s.substr(i-last,last)<<'\n';
  55.             return build(i+last+1,last+1);
  56.         }
  57.         else if(s[i1]<s[i2] && ret==1+rec(i+c+1,c+1)){
  58.             cout<<s.substr(i-last,last)<<'\n';
  59.             return build(i+c+1,c+1);
  60.         }
  61.         assert(0);
  62.     }else{
  63.         return build(i+1,1);
  64.     }
  65. }
  66. int main() {
  67.     boAshraf
  68.     File();
  69.     int t = 1;
  70. //    cin >> t;
  71.     while (t--) {
  72.         sol();
  73.     }
  74.     return 0;
  75. }
  76.  
  77. void sol() {
  78.     cin>>s;
  79.     n=sz(s);
  80.     memset(common,-1,sizeof common);
  81.     memset(dp,-1,sizeof dp);
  82.     cout<<rec(0,0)<<'\n';
  83.     build(0,0);
  84. }
  85.  
  86. void File() {
  87. #ifndef ONLINE_JUDGE
  88.     freopen("input.txt", "r", stdin);
  89.     freopen("output.txt", "w", stdout);
  90. #endif
  91. }
Advertisement
Add Comment
Please, Sign In to add comment