牛客小白月赛 22 C. 交换游戏

链接

https://ac.nowcoder.com/acm/contest/4462/C

题意

给出一个长度为 $12$ 的 $01$ 字符串,$011$ 可更换为 $100$,$110$ 可更换为 $001$,求最后字符串中 $1$ 的个数

思路

因为有最多 $1e5$ 次询问,所以可以预处理出所有 $2^{12}$ 种情况的答案
在记忆化搜索时,对于每种情况,搜索出所有的 $011$ 和 $110$,依次进行比较

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,res[N];
bool st[N];
int dfs(int x) {
if(st[x]) return res[x];
int cnt=0;
for(int i=11;i>=0;i--) if((x>>i)&1) cnt++;
for(int i=11;i>=2;i--) if(((x>>(i-1))&1)&&(((x>>i)&1)^((x>>(i-2))&1))) cnt=min(cnt,dfs(x^(7<<(i-2))));
st[x]=true;
return res[x]=cnt;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int lim=(1<<12)-1;
for(int i=0;i<=lim;i++) if(!st[i]) dfs(i);
cin>>n;
for(int i=1;i<=n;i++) {
string s;
cin>>s;
int t=0;
for(int i=0;i<s.length();i++) if(s[i]=='o') t|=(1<<(11-i));
cout<<res[t]<<endl;
}
return 0;
}