题解: SAM板子题 但是要做一个小dp
很显然 有个dp就是
$ dp[i]=min(dp[i],dp[j]+b) $若在子串[1,j-1]中子串[j,i]存在
那么我们就用SAM维护每个子串最早出现在字符串中的位置 然后check一下就行了
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <stack> #include <queue> #include <cmath> #include <set> #include <map> #define mp make_pair #define pb push_back #define pii pair<int,int> #define link(x) for(edge *j=h[x];j;j=j->next) #define inc(i,l,r) for(int i=l;i<=r;i++) #define dec(i,r,l) for(int i=r;i>=l;i--) const int MAXN=3e5+10; const double eps=1e-8; #define ll long long using namespace std; const int inf=1e9; struct edge{int t;edge*next;}e[MAXN<<1],*h[MAXN],*o=e; void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;} ll read(){ ll x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); return x*f; } int n,a,b; char str[MAXN]; int fa[MAXN],dis[MAXN],ch[MAXN][26],minn[MAXN]; int cnt,cur,rt; void built(int x){ int last=cur;cur=++cnt;dis[cur]=dis[last]+1;int p=last;minn[cur]=dis[cur]; for(;p&&!ch[p][x];p=fa[p])ch[p][x]=cur; if(!p)fa[cur]=rt; else { int q=ch[p][x]; if(dis[q]==dis[p]+1)fa[cur]=q; else{ int nt=++cnt;dis[nt]=dis[p]+1;minn[nt]=inf; memcpy(ch[nt],ch[q],sizeof(ch[q])); fa[nt]=fa[q];fa[q]=fa[cur]=nt; for(;ch[p][x]==q;p=fa[p])ch[p][x]=nt; } } } void dfs(int x){ link(x){dfs(j->t);minn[x]=min(minn[x],minn[j->t]);} } int dp[MAXN]; int main(){ n=read();a=read();b=read(); scanf("%s",str+1); cnt=cur=rt=1;minn[rt]=inf; inc(i,1,n)built(str[i]-'a'); inc(i,1,cnt)add(fa[i],i); dfs(rt); inc(i,1,n)dp[i]=inf; inc(i,1,n){ int temp=rt; inc(j,i,n){ if(j==i)dp[j]=min(dp[j],dp[j-1]+a); int t=str[j]-'a';temp=ch[temp][t]; if(minn[temp]<i)dp[j]=min(dp[j],dp[i-1]+b); } } printf("%d ",dp[n]); }