题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6676
Source
官方题解
照着题解写的代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1<<21;
char s[N+10];
int num[N+10];
int main()
{
int t, cnt, tot, ans;
scanf("%d",&t);
while(t--){
scanf("%s",s);
int len=strlen(s);
cnt=1; tot=ans=0;
for(int i=0;i<len;++i){
if(s[i]=='?') cnt++;
else{
num[tot++]=cnt;
cnt=1;
}
}
num[tot++]=cnt;
sort(num,num+tot);
int tmp=num[tot-1], l=0;
while(tmp){
l++;
tmp>>=1;
}
l--;
ans=1<<l;
num[tot-1]-=ans;
if(l) l--;
while(l){
sort(num,num+tot);
if(num[tot-1]>=(1<<l)){
num[tot-1]-=(1<<l);
ans+=(1<<l);
}
l--;
}
for(int i=0;i<tot;++i) ans^=(num[i]&1);
printf("%d\n",ans);
}
return 0;
}
自己比赛的时候写的代码,比上面的还快一点
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1<<21;
char s[N+10];
int num[N+10];
int lowbit(int x){
return x&(-x);
}
int main()
{
int t, cnt, tot, ans, tmp, lb, flag, no;
scanf("%d",&t);
while(t--){
tot=0, flag=0, no=0;
scanf("%s",s);
int len=strlen(s);
cnt=1;
for(int i=0;i<len;++i){
if(s[i]=='?') cnt++;
else{
num[tot++]=cnt;
cnt=1;
}
}
num[tot++]=cnt;
sort(num,num+tot);
int ans=num[tot-1];
for(int i=tot-2;i>=0;--i){
if(flag){
tmp=num[i]&1;
ans^=tmp;
continue;
}
tmp=ans+1;
if((tmp&ans)==0){
flag=1;
i++;
continue;
}
tmp=ans+2;
if((tmp&ans)==0){
flag=1;
i++;
continue;
}
tmp=ans;
int now=1, lb;
while(tmp){
if((tmp&1)==0) lb=now;
now<<=1;
tmp>>=1;
if(((tmp+1)&tmp)==0) break;
}
if(num[i]>=lb){
ans+=lb;
num[i]-=lb;
if(num[i]>=lb){
int ta=num[i]&1, tb=ans&1;
int l=1;
while(ans){
ans>>=1;
l<<=1;
}
ans=l-1;
ans=ans^(ta^tb^1);
flag=1;
}else{
sort(num,num+i+1);
i++;
}
}else{
ans+=lb;
no+=lb;
i++;
}
}
printf("%d\n",ans-no);
}
return 0;
}