[AGC007F] Shik and Copying String(贪心)

首先,描出字母转移的路径,发现每个字母的转移路径都是一条折线

折线满足以下性质:

  • 折线不可相交
  • 折线覆盖整个T串
  • 折线只能向右或向下延伸
  • 一个字母转移路径上拐点个数,等于这个字母转移最少需要新开几个字符

易得,答案等于折线上拐点个数的最大值

如何求解?

使用贪心,从T串从右往左确定折线,使得折线尽量靠右。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=1e6+5;
char s[N],t[N];
int len,ans=0,head=1,tail=0,q[N];
int main(){
    scanf("%d",&len);
    scanf("%s%s",s+1,t+1);
    if(strcmp(s+1,t+1)==0){printf("0
");return 0;}
    int p=len,pos=len;
    while(p>0){
        if(t[p-1]!=t[p]){
            pos=min(pos,p);
            while(pos>0&&s[pos]!=t[p]) pos--;
            if(s[pos]!=t[p]){printf("-1
");return 0;}
            while(head<=tail){
                if(q[head]-(tail-head+1)+1>p) head++;
                else break;
            }
            q[++tail]=pos;
            if(p!=pos) ans=max(ans,tail-head+1);
        }
        p--;
    }
    printf("%d
",ans+1);
    return 0;
}
原文地址:https://www.cnblogs.com/HarryPotter-fan/p/13896376.html