题解:AT_abc427_f [ABC427F] Not Adjacent

· · 题解

折半搜索模板题。

因为 n\le 60,而选数的时候必须隔一个位置才能继续选,所以最终状态数大概略大于 2^{30} 左右,加上折半搜索就是大于 2^{16},但是肯定能过就是了。

关于折半搜索的原理,大概就是从起点和终点各搜索一半的状态,然后在中间计算,复杂度就从 x^n 变成了 x^{{\frac{n}{2}}+1}。

注意 n 的值是 1 的时候要特判。

别问我怎么知道的,赛时被这件事情卡了好久结果赛后突然想明白了。

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 120;
int n,m,ans,cnt,a[N];
unordered_map<int,int>mp;
void dfs(int x,int sum,int limit,int flag){
    if(flag==1 && (x==n/2)){
        dfs(x+1,(sum+a[x])%m,limit,flag);
        return;
    }
    if(flag==100 && (x==n/2)){
        dfs(x+1,sum,limit,flag);
        return;
    }
    if(x>limit){
        sum%=m;
        if(limit==n/2) {
            mp[sum]++;
        }else{
            if(sum==0) ans+=mp[0];
            else ans += mp[m-sum];
        }
        return;
    }
    if(!(flag==1 && x==(n/2)-1))dfs(x+2,(sum+a[x])%m,limit,flag);
    dfs(x+1,sum,limit,flag);
}
void Main(){
    cin>>n>>m;
    for(int i = 1; i<=n; i++){
        cin>>a[i];
        a[i]%=m;
    }
    if(n==1){
        if(a[1]%m==0) cout<<2<<endl;
        else cout<<1<<endl;
        return;
    }
    dfs(1,0,n/2,1);
    dfs(n/2+2,0,n,0);
    mp.clear();
    dfs(1,0,n/2,100);
    dfs(n/2+1,0,n,0);
    cout<<ans<<"\n";
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T = 1;
    while(T--){
        Main();
    }
    return 0;
}