906E - Reverses - CodeForces Solution


dp string suffix structures strings *3300

Please click on ads to support us..

C++ Code:

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

int n;
char s[1000010],ch1[500010],ch2[500010];

struct palTree{
    int cnt,last,len[1000010],trie[1000010][26],fail[1000010],diff[1000010],slink[1000010];
    palTree()
    {
        cnt=1,len[1]=-1,fail[0]=1,slink[0]=1;
    }
    void ins(int ch,int i,char s[]){
        int p=last;
        while(i-len[p]<=0 || s[i-len[p]-1]!=s[i]) p=fail[p];
        if(!trie[p][s[i]-'a']){
            len[++cnt]=len[p]+2;
            int q=fail[p];
            while(i-len[q]<=0 || s[i-len[q]-1]!=s[i]) q=fail[q];
            fail[cnt]=trie[q][ch];
            trie[p][ch]=cnt;
            diff[cnt]=len[cnt]-len[fail[cnt]];
            slink[cnt]=(diff[cnt]==diff[fail[cnt]]) ? slink[fail[cnt]] : fail[cnt];
        }
        last=trie[p][ch];
    }
}tree;

int dp[1000010],g[1000010],pre[1000010];

int main(){
    scanf("%s%s",ch1+1,ch2+1);
    n=strlen(ch1+1)<<1;
    for(int i=1;i<=n;i++){
        if (i&1) s[i]=ch1[i+1>>1];
        else s[i]=ch2[i>>1];
    }
    for(int i=1;i<=n;i++){
        dp[i]=0x3f3f3f3f;
        tree.ins(s[i]-'a',i,s);
        if(!(i&1) && s[i]==s[i-1] && dp[i-2]<dp[i]){
            dp[i]=dp[i-2],pre[i]=i-2;
        }
        for(int p=tree.last; p; p=tree.slink[p]){
            g[p]=i-tree.len[tree.slink[p]]-tree.diff[p];
            if(tree.slink[p]!=tree.fail[p] && dp[g[p]]>dp[g[tree.fail[p]]]) g[p]=g[tree.fail[p]];
            if(!(i&1) && dp[i]>dp[g[p]]+1) dp[i]=dp[g[p]]+1,pre[i]=g[p];
        }
    }
    if(dp[n]==0x3f3f3f3f){
        puts("-1");return 0;
    }
    printf("%d\n",dp[n]);
    for(int i=n; i>=1; i=pre[i])
        if(i-pre[i]!=2) printf("%d %d\n",(pre[i]>>1)+1,i>>1);
}/*1694671193.5587075*/


Comments

Submit
0 Comments
More Questions

1302. Deepest Leaves Sum
1209. Remove All Adjacent Duplicates in String II
994. Rotting Oranges
983. Minimum Cost For Tickets
973. K Closest Points to Origin
969. Pancake Sorting
967. Numbers With Same Consecutive Differences
957. Prison Cells After N Days
946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST