1828E - Palindrome Partition - CodeForces Solution


data structures dp hashing strings

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

vector<int> manacher(string s) {
    string t = "#";
    for (auto c : s) {
        t += c;
        t += '#';
    }
    int n = t.size();
    vector<int> r(n);
    for (int i = 0, j = 0; i < n; i++) {
        if (2 * j - i >= 0 && j + r[j] > i) {
            r[i] = std::min(r[2 * j - i], j + r[j] - i);
        }
        while (i - r[i] >= 0 && i + r[i] < n && t[i - r[i]] == t[i + r[i]]) {
            r[i] += 1;
        }
        if (i + r[i] > j + r[j]) {
            j = i;
        }
    }
    return r;
}

int main(){
    int t; cin>>t; while(t--){
        int n; cin>>n; 
        string s; cin>>s;
        auto res=manacher(s);
        vector<int> next(n+1,-1),st;
        for(int i=0;i<n;i++){
            st.push_back(i);
            //cout<<res[i]<<' ';
            while(!st.empty()&&st.back()>i-res[2*(i+1)]/2){
                next[st.back()]=2*i+2-st.back();
                st.pop_back();
            }
        }
        vector<int> dp(n+1,0);
        long long ans=0;
        for(int i=n-1;i>=0;i--){
            if(next[i]!=-1) dp[i]=dp[next[i]]+1;
            ans=ans+dp[i];
        }
        cout<<ans<<endl;
    }
}


Comments

Submit
0 Comments
More Questions

402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements