P6521 [CEOI 2010] pin (day2) 题解

· · 题解

P6521 [CEOI 2010] pin (day2)

原题链接 P6521 [CEOI 2010] pin (day2)

题意

给定 n 个长度为 4 的字符串,求两两字符串恰好有 d 个位置不同的数量 。

思路

做法

将确定的位置压缩成一个二进制数,字符串转化为一个 36 进制数编码 。用 cnt_{bit} 来记录压缩位置为 bit 的位置上两两匹配的个数, map 用来维护并存储确定位置的编码,设个数为 x , 那么 :

cnt_{bit} = \sum_{x=0}^{36^4-1} \frac{mp_x \times (mp_x-1) }{2}

对于相同位置恰好为 bit 的方案数 ,用容斥计算,考虑所有包含 bit 的位置 all ,对于 bit 多出的位置数量为 c ,那么当 c 为偶数时是加贡献,c 为奇数时是减贡献。用 clac(bit) 表示 bit 的二进制为上为 1 的数量,具体的公式为。

ans = \sum_{clac(bit) = 4-d} \sum_{bit \in all} (-1)^{clac(all-bit)} \times cnt_{all}

时间复杂度 O(16nlogn) 。

code

#include <bits/stdc++.h>
using namespace std;
#define int long long 
const int N = 2e5+5;
int n,d,t;
int a[N][4];
int get(char c){
    if(c>='0'&&c<='9')return c-'0';
    else return c-'a'+10;
}
int cnt[1<<4];
int calc(int x){
    int res=0;
    while(x){
        res += x%2;
        x /=2;
    }
    return res;
}
map<int,int>mp[1<<4];
signed main()
{
    //freopen("data.txt","r",stdin);
    cin>>n>>d;
    t=4-d;
    for(int i=1;i<=n;i++){
        for(int j=0;j<4;j++){
            char x;
            cin >> x;
            a[i][j] = get(x);
        }
        for(int bit=0;bit<(1<<4);bit++){
            int tot = 0;
            for(int j=0;j<4;j++){
                if((bit>>j)&1){
                    tot += a[i][j] * pow(36,j);
                }
            }
            if(mp[bit].count(tot)){
                cnt[bit]-= mp[bit][tot]*(mp[bit][tot]-1)/2;
                mp[bit][tot]++;
                cnt[bit]+= mp[bit][tot]*(mp[bit][tot]-1)/2;
            }
            else{
                mp[bit][tot]=1;
            }
        }
    }
    int ans = 0;
    for(int bit=0;bit<(1<<4);bit++){
        if(calc(bit)==t){
            int res = 0;
            for(int all=0;all<(1<<4);all++){
                if((bit&all) == bit){
                    int c = calc(all-bit);
                    res += (c%2==0?1ll:-1ll) * cnt[all];
                }
            }
            ans += res;
        }
    }
    cout<<ans<<endl;
    return 0;
}