【GDOI2016模拟4.22】无界单词

此题很神奇请看大神题解。点这里
我的代码

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <iostream>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define N 65
#define mo 500000
#define ll long long
int n,next[N],jy,jy1,len;
ll f[N],k,ans[N],er[N];
ll hash(int len,int i,int j)
{
    ll x=0,y=0;
    fo(k,i-j+1,len) x=x*2+ans[k];
    fo(k,1,len-i+j) y=y*2+ans[k];
    return x==y;
}
ll hzj()
{
    memset(f,0,sizeof(f));
    fo(i,1,n)
    {
        if (i<len && next[i]==0) f[i]=1; 
        if (i<len) continue;
        f[i]=er[(i-len)];
        fo(j,1,i/2)
        {
            ll x;
            if (j>=len) x=er[(i-2*j)];
            if (len>j && len<=i-j) x=er[(i-2*j-len+j)];
            if (len>i-j) x=hash(len,i,j);
            f[i]-=x*f[j];
        }
    }
    return f[n];
}
void kmp()
{
    if (len==1) return;
    while (jy!=0 && ans[len]!=ans[jy+1]) jy=next[jy];
    if (ans[len]==ans[jy+1]) jy++;
    next[len]=jy;
}
int main()
{
    freopen("word.in","r",stdin);freopen("word.out","w",stdout);
    er[0]=1;fo(i,1,63) er[i]=er[i-1]*2;
    int ak;scanf("%d",&ak);
    while (ak-->0)
    {
        scanf("%d%lld",&n,&k);jy=len=0;
        memset(next,0,sizeof(next));
        ll lh=hzj();printf("%lld\n",lh);
        for(len=1;len<=n;len++)
        {
            ans[len]=0;jy1=jy;
            kmp();
            ll lh=hzj();
            if (lh<k)
            {
                jy=jy1;ans[len]=1;k-=lh;kmp();
            }
        }
        fo(i,1,n) printf("%c",ans[i]==0?'a':'b');
        printf("\n");
    }
    fclose(stdin);fclose(stdout);
}

你可能感兴趣的:(dp)