【BZOJ4180】—字符串计数(二分答案+后缀自动机+矩阵快速幂)

传送门

定义f[i][j]f[i][j]为以ii开头jj结尾的最短的不会被别的串表示出来的串
这个可以在SamSamdpdp得到
考虑二分答案
于是只需要看midmid次拼出的串是否比nn大即可

#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
    static char ibuf[RLEN],*ib,*ob;
    (ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ob==ib)?EOF:*ib++;
}
#define gc getchar
inline int read(){
    char ch=gc();
    int res=0,f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
#define ll long long
#define re register
#define pii pair<int,int>
#define pic pair<int,char>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
#define poly vector<int>
template<class T>inline void chemx(T &a,T b){a<b?a=b:0;}
template<class T>inline void chemn(T &a,T b){a>b?a=b:0;} 
cs int N=100005;
struct mat{
	ll a[4][4];
	mat(){memset(a,127/3,sizeof(a));}
	friend inline mat operator *(cs mat &a,cs mat &b){
		mat c;
		for(int i=0;i<4;i++)
		for(int k=0;k<4;k++)
		for(int j=0;j<4;j++)
		chemn(c.a[i][j],a.a[i][k]+b.a[k][j]);
		return c;
	}
};
inline mat mksm(mat a,ll b){
	mat res;
	memset(res.a,0,sizeof(res.a));
	for(;b;b>>=1,a=a*a)if(b&1)res=res*a;
	return res;
}
namespace Sam{
	cs int M=N<<1;
	int nxt[M][4],fa[M],len[M],tot,f[M][4],last;
	inline void init(){
		last=tot=1;
	}
	inline void insert(int c){
		int cur=++tot,p=last;last=cur;
		len[cur]=len[p]+1;
		for(;p&&!nxt[p][c];p=fa[p])nxt[p][c]=cur;
		if(!p)fa[cur]=1;
		else{
			int q=nxt[p][c];
			if(len[p]+1==len[q])fa[cur]=q;
			else{
				int clo=++tot;
				memcpy(nxt[clo],nxt[q],sizeof(nxt[q]));
				fa[clo]=fa[q],len[clo]=len[p]+1;
				for(;p&&nxt[p][c]==q;p=fa[p])nxt[p][c]=clo;
				fa[q]=fa[cur]=clo;
			}
		}
	}
	int vis[M];
	void dfs(int u){
		if(vis[u])return;
		vis[u]=1;
		for(int i=0;i<4;i++){
			int v=nxt[u][i];
			if(!v)f[u][i]=1;
			else{
				dfs(v);
				for(int j=0;j<4;j++)
				chemn(f[u][j],f[v][j]+1);
			}
		}
	}
	inline void build(char *s){
		init();
		for(int i=1,len=strlen(s+1);i<=len;i++)insert(s[i]-'A');
		memset(f,127/3,sizeof(f)),dfs(1);	
	}
	mat now;
	inline bool check(ll t,ll mx){
		mat v=mksm(now,t);
		ll res=2e18;
		for(int i=0;i<4;i++)
		for(int j=0;j<4;j++)
		chemn(res,v.a[i][j]);
		return res>=mx;
	}
	inline void calc(ll n){
		for(int i=0;i<4;i++)
		for(int j=0;j<4;j++)
		if(nxt[1][i])now.a[i][j]=f[nxt[1][i]][j];
		ll l=1,r=n,res=l;
		while(l<=r){
			ll mid=(l+r)>>1;
			if(check(mid,n))r=mid-1,res=mid;
			else l=mid+1;
		}
		cout<<res<<'\n';
	}
} 
ll n;
char s[N];
int main(){
	scanf("%lld",&n);
	scanf("%s",s+1);
	Sam::build(s);
	Sam::calc(n);
}
posted @ 2019-09-27 18:00  Stargazer_cykoi  阅读(116)  评论(0编辑  收藏  举报