P6521 [CEOI 2010] pin (day2)
原题链接 P6521 [CEOI 2010] pin (day2)
题意
给定 个长度为 的字符串,求两两字符串恰好有 个位置不同的数量 。
思路
- 我们不方便求字符不同的方案数,但求某几位上字符相同的方案数是容易的。
- 我们可以在确定 个位置中的任意几个位置时,求得两两匹配的个数,而其他位置不知道 。
- 那么我们可以求得的是至少在某几个位置上相同的两两匹配个数。
做法
将确定的位置压缩成一个二进制数,字符串转化为一个 进制数编码 。用 来记录压缩位置为 的位置上两两匹配的个数, 用来维护并存储确定位置的编码,设个数为 , 那么 :
对于相同位置恰好为 的方案数 ,用容斥计算,考虑所有包含 的位置 ,对于 多出的位置数量为 ,那么当 为偶数时是加贡献, 为奇数时是减贡献。用 表示 的二进制为上为 的数量,具体的公式为。
时间复杂度 。
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;
}