分数
题目
[KenOI 2025] 异或题
题意
给定 组询问,每组给出一个整数 。要求找到两个整数 ,满足 且 ,并输出 的最大可能值。
思路
正解困难,采用逆向构造:初始取 ,满足 ;从高位到低位贪心调整 ,最大化异或和。
用 表示 的二进制第 位:
- 当前位 :若 且 ,令 ,答案累加 。
- 当前位 :将 改为 (和不变);仅当 时执行调整,使 差值最小。
正确性:二进制性质 ,高位优先贪心最优; 越接近,越易满足低位扩容条件。
复杂度:拆分 的二进制位,共 位,总复杂度 。
AC代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
int T, n;
int b[40], m;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> T;
while (T--)
{
cin >> n;
m = 0;
int x = n, y = 0, t = n;
while (n > 0)
{
b[++m] = n % 2;
n /= 2;
}
n = t;
for (int i = m; i >= 1; i--)
{
int p = (1 << (i - 1));
if (b[i] == 0 && x + p <= t && y + p <= t)
{
y += p;
x += p;
}
else if (b[i] == 1)
{
if (abs(x - y) > abs((x - p) - (y + p)))
{
x -= p;
y += p;
}
}
}
cout << x + y << "\n";
}
return 0;
}时间复杂度:
异或积
题意
给定长度为 的数组 ,定义异或积变换:将数组 替换为数组 ,其中
求对数组进行 次异或积变换后的结果。
核心结论
设数组总异或和 ,则一次异或积变换的结果为:
变换规律
- 为奇数: 时,结果恒为一次变换后的数组
- 为偶数:
- 为奇数:结果为一次变换后的数组
- 为偶数:结果为原数组
AC代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int n;
long long k;
cin >> n >> k;
vector<unsigned int> a(n);
unsigned int s = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
s ^= a[i];
}
if (n % 2 == 1 && k > 0)
{
for (int i = 0; i < n; i++)
cout << (s ^ a[i]) << " \n"[i == n - 1];
}
else if (n % 2 == 0 && k % 2 == 1)
{
for (int i = 0; i < n; i++)
cout << (s ^ a[i]) << " \n"[i == n - 1];
}
else
{
for (int i = 0; i < n; i++)
cout << a[i] << " \n"[i == n - 1];
}
}
return 0;
}时间复杂度:
[BCSP-X 2024 6 月初中组] 打孔纸带
题意简述
给定若干条 01 打孔纸带,机器对两条纸带的每一位进行 与、或、异或 其中一种运算。 求最少需要新制作多少条纸带,才能唯一确定机器的运算规则。
核心思路
每一位独立判断:
- 要唯一区分三种运算,该位必须同时出现 0 和 1,且 至少两个 1。
- 对每一位计算需要补充的最少纸带数,答案取所有位的最大值。
AC代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1555;
int n, ans;
int cnt0[N], cnt1[N];
string s;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
{
cin >> s;
int len = s.size();
n = max(n, len);
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '0') cnt0[i]++;
else cnt1[i]++;
}
}
for (int i = 0; i < n; i++)
{
int res = 0;
if (cnt0[i] == 0) res++;
if (cnt1[i] < 2) res += 2 - cnt1[i];
ans = max(ans, res);
}
cout << ans;
return 0;
}时间复杂度:
[CSP-S 2020] 动物园
核心思路
- 本题本质是二进制位运算, 和饲料编号无意义,直接忽略
- 用按位或统计所有动物已存在的二进制位
- 标记必须为 的二进制位,剩余自由位数量为
- 答案 = 总方案数 ( 为已有动物数量)
- 特殊情况: 且 时,输出 字符串
AC代码
#include <bits/stdc++.h>
#define ULL unsigned long long
using namespace std;
int main() {
int n, m, c, K;
cin >> n >> m >> c >> K;
ULL flag = 0, g = 0;
// 统计已存在的二进制位
for (int i = 0; i < n; i++)
{
ULL x;
cin >> x;
flag |= x;
}
// 标记必须为 0 的位
while (m--)
{
int p;
int tmp;
cin >> p >> tmp;
if ((flag >> p & 1) == 0)
g |= 1ULL << p;
}
// 计算 2^t
ULL ans = 1;
for (int i = 0; i < K; i++)
{
if ((g >> i & 1) == 0)
ans <<= 1;
}
// 溢出特判
if (ans == 0 && n == 0)
{
cout << "18446744073709551616" << "\n";
return 0;
}
ans -= n;
cout << ans << "\n";
return 0;
}时间复杂度: