# 最长公共子序列【省选模拟赛】

## 经典LCS问题的毒瘤版本

Posted by yjjr's blog on March 4, 2018

n<=1e5,m<=26

# 分析

O(n)判断两个长度为n的串的LCS长度为n-1

# code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
using namespace std;
{
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=1e5+6;
ll f[maxn][2][2][2],ans;
int n,m;char st[maxn];
int main()
{
scanf("%s",st);
if(n==1){cout<<m-1<<endl;return 0;}
f[1][1][1][1]=1;
if(st[0]==st[1])f[1][1][0][0]=m-1;else f[1][1][0][1]=1,f[1][1][0][0]=m-2;
rep(i,1,n-1)
rep(k,0,1)
rep(l,0,1)
rep(t,0,1)
if(f[i][k][l][t])
rep(j,1,m){
int X=l+i-1,Y=t+i-1;
if(j==st[i-1]-'a'+1)X=max(X,k+i-2+1);
if(j==st[i-1]-'a'+1)Y=max(Y,k+i-2+1);
if(j==st[i]-'a'+1)Y=max(Y,l+i-1+1);
int Z=Y;
if(j==st[i+1]-'a'+1)Z=max(Z,max(l-i-1+1,t+i-1+1));
X-=(i-1);Y-=i;Z-=i;
if(X>=0&&Y>=0&&Z>=0)f[i+1][X][Y][Z]+=f[i][k][l][t];
}
rep(k,0,1)
rep(l,0,1)ans+=f[n][k][0][l];
cout<<ans<<endl;
return 0;
}