这是蒟蒻第一篇题解,所以这里讲一个蒟蒻解法
首先我们发现题目中给出的样例有很多是和原值相等的!所以可以写出骗分代码:
#include<bits/stdc++.h>
using namespace std;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
cout<<n<<endl;
}
return 0;
}当然,这显然是太过高级了,评测机根本不能核对出正确的答案,所以需要修改。
我们观察异或的含义发现:
- 当 的某一二进制位上的值为 时, 和 在这一位上只有两种可能:
要么 在这一位上为 ,要么 在这一位上为 。 - 当 的某一二进制位上的值为 时, 和 在这一位上的值也只有两种可能:
要么都为 ,在这一情况下,我们要保证 和 都比 小,就要确保 前面还有至少 个
要么都为 。
AC code:
#include<bits/stdc++.h>
#define int long long
#define cha char
#define con const int
#define endl '\n'
#define ULL unsigned long long
using namespace std;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int lenn=0;
for(int i=0;(n>>i);i++){
lenn+=((n>>i)&1);
}//蒟蒻写法,求一共有几个位置上为 1
int cnt1=0,cnt2=0;
int ans1=0;
int ans2=0;
for(int i=0;(n>>i);i++){
if((n>>i)&1){
lenn--;//遇到前面的位置上有的 1 的数量就减 1
if(cnt1>0){
cnt1--;
ans2|=(1<<i);
continue;
} //当需要维护 ans1 不大于n时,这一位上的 1 就由 ans2 来完成
else if(cnt2>0){
cnt2--;
ans1|=(1<<i);
continue;
}//当需要维护 ans2 不大于n时,这一位上的 1 就由 ans1 来完成
ans1|=(1<<i); //否则默认ans1来完成
}
else{//当为0是有两种情况,为[1,1]和[0,0]
if(lenn<2){
continue;
}//需要为[0,0]情况时
ans1|=(1<<i);
ans2|=(1<<i);
cnt1++;
cnt2++;//能为[1,1]情况时一定为[1,1]更优
}
}
cout<<ans1+ans2<<endl;
}
return 0;
}