题解:P1316 Mivik 写书

· · 题解

对我这个奥数不学的人来说容斥还是太难了。
初看题目我们发现 m 过大,无法突破,但是 n 很小,考虑突破。首先这是一道紫题,所以我们可以假设他是一道状压。
然后发现了一个性质:不同的长度的子串,贡献不相通,所以枚举子串长度搞答案。枚举状态表示子串的头。但是会出现重复,所以容斥就有用了。
状压并并查集,得到没有约束的位置,设有 tmp 个,对答案的贡献是

(-1)^{popcount(s)} \times m^{cnt}

其中的 s 表示子串头位置的状压后的样子。
实在看不懂就看看代码吧。
最后注意几个坑点:

  1. 并查集的统计自由点不要用find函数,使用已经有的祖先数组。
  2. 十年 OI 一场空,不开什么见祖宗。
  3. 快读快写要加上。
    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int mod=1e9+7;
    int n,m,cd,ans,i,j,k,pp,tmp,f[25],vis[25];
    int read(){
     int s=0,f=1;
     char ch=getchar();
     while(ch<'0' || ch>'9'){
         if(ch=='-')f=-1;
         ch=getchar();
     }
     while(ch>='0' && ch<='9'){
         s=s*10+ch-'0';
         ch=getchar();
     }
     return s*f;
    }
    void write(int x){ 
     if(x<0){
         putchar('-');
         x=-x;
     }
     if(x>9)write(x/10);
     putchar(x%10+'0');
    }
    int fpow(int a,int b){
     int ans=1;
     while(b){
         if(b&1) ans=ans*a%mod;
         a=a*a%mod;b>>=1;
     }
     return ans;
    }
    int find(int x){
     return (x==f[x]?x:f[x]=find(f[x]));
    }
    signed main(){
     n=read();m=read();
     for(cd=1;cd<=n;cd++)//枚举长度,因为各个长度的子串答案贡献无关
         for(i=0;i<(1<<(n-cd+1));i++){//枚举真实的子串开始位置集合
             pp=__builtin_popcount(i);
             if(pp==0) continue;//根本没有贡献直接丢掉
             memset(vis,-1,sizeof(vis));//是否有这个子串
             for(j=0;j<=cd;j++) f[j]=j;
             for(j=0;j<=n-cd;j++)
                 if(i>>j&1)
                     for(k=0;k<=cd-1;k++)
                         if(vis[j+k]==-1) vis[j+k]=k;//没有出现过标记
                         else f[find(k)]=find(vis[j+k]);//出现过合并
             tmp=0;//答案时间!
             for(j=0;j<=cd-1;j++) if(find(j)==j) tmp++;
             for(j=0;j<=n-1;j++) if(vis[j]==-1) tmp++;
             tmp=fpow(m,tmp);
             if(pp&1) ans=(ans+tmp)%mod;
             else ans=(ans-tmp+mod)%mod;
         }
     ans=ans*fpow(fpow(m,n),mod-2)%mod;
     write(ans);
    }