跳到正文

题解

[KenOI 2025] 异或题题解

In_our_Sky约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年12月7日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 3 分钟
题目
P14664

版本

  1. v2当前
  2. v1

这是蒟蒻第一篇题解,所以这里讲一个蒟蒻解法
首先我们发现题目中给出的样例有很多是和原值相等的!所以可以写出骗分代码:

C++
#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;
}

当然,这显然是太过高级了,评测机根本不能核对出正确的答案,所以需要修改。
我们观察异或的含义发现:

  • 当 nn 的某一二进制位上的值为 11 时, aa 和 bb 在这一位上只有两种可能:
    要么 aa 在这一位上为 11 ,要么 bb 在这一位上为 11 。
  • 当 nn 的某一二进制位上的值为 00 时,aa 和 bb 在这一位上的值也只有两种可能:
    要么都为 11 ,在这一情况下,我们要保证 aa 和 bb 都比 nn 小,就要确保 nn 前面还有至少 22 个 11
    要么都为 00 。

AC code:

C++
#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;
}
原文