Codeforces LATOKEN Round 1 (Div. 1 + Div. 2)
E: Lost Array
题目翻译
给你 个数,分别是,目的是计算这 个数的异或的值。你可以通过询问 个数的方式,来获得任意 个数的异或值。
- 如果无法求得 个数的异或值,输出
-1
。 - 如果可以求得 个数的异或值,需要使用最少的询问次数。输出 个数的异或值。
数据范围:。
题目思路
首先判断是否能求得这 个数的异或值,如果能够求得,就计算出询问次数。
这里抽象一下题意,理解为一个位置移动问题。刚开始在座标轴起点 , 每次可以向左或者右移动共 位,但是不能走到比 小的位置,也不能走到大于 的位置,问能不能到达 。位置移动的所在位置相当于当前已经询问之后的异或的数的值。移动中向左移动 位,向右边移动 位,,这相当于取的 个数中,有 个数是之前选择过的,异或之后需要将它移出,有 个数是之前没有选择过的,异或之后,需要将他们添加到选择的列表中。这样的问题,可以用BFS解决。每次移动可以向左移动 ,那么就会向右移动 位。如果发现到不了 ,就表示到不了目的地。
参考代码
#include <bits/stdc++.h>
using namespace std;
int n, k;
int dis[555]; //到达该位置,需要的操作次数
int method[555]; //到达该位置的时候,向右移动的位数
int prev1[555]; //到达该位置的前一个位置
const int inf = 0x3f3f3f3f;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> k;
queue<int> Q;
Q.push(0);
memset(prev1, 0x3f, sizeof prev1);
memset(dis, 0x3f, sizeof dis);
dis[0] = 0;
prev1[0] = -1;
// 遍历每一个位置,判断它能到达的位置。
while (!Q.empty()) {
auto x = Q.front();
Q.pop();
// i 是向右移动的位数
for (int i = 0; i <= k; ++i) {
// 不能移动到n的右边,不能移动到n的左边
if (i + x <= n and k - i <= x) {
// 下一个位置
int nex = x + i - (k - i);
// 如果下一个位置之前没有访问过
if (dis[nex] == inf) {
// 设定下一个位置的前一个位置为当前位置
prev1[nex] = x;
// 设定下一个位置的到达方式是向右移动了i位(向左移动了k-i位)
method[nex] = i;
// 到达下一个位置,所需要的询问次数
dis[nex] = dis[x] + 1;
Q.push(nex);
}
}
}
}
// 如果发现终点不可达
if (dis[n] == inf) {
cout << -1 << endl;
} else {
vector<int> path;
vector<int> select, unselect;
// 设定走过的路径
for (int i = n; i != -1; i = prev1[i]) {
path.push_back(i);
}
reverse(path.begin(), path.end());
// 将n个数都设定为未被选择
for(int i = 0; i < n; ++i){
unselect.push_back(i + 1);
}
int ret = 0;
for (int i = 1; i < path.size(); ++i) {
// 到达这个点的方法中,向右移动了nosel,向左移动了sel
int nosel = method[path[i]];
int sel = k - method[path[i]];
vector<int> tselect, tunselect;
for (int i = 0; i < nosel; ++i) {
tunselect.push_back(unselect.back());
unselect.pop_back();
}
for (int i = 0; i < sel; ++i) {
tselect.push_back(select.back());
select.pop_back();
}
cout << "?";
for (auto it : tselect) {
cout << " " << it;
}
for (auto it : tunselect) {
cout << " " << it;
}
cout << endl;
cout.flush();
select.insert(select.end(), tunselect.begin(), tunselect.end());
unselect.insert(unselect.end(), tselect.begin(), tselect.end());
int tmp;
cin >> tmp;
ret ^= tmp;
}
cout << "! " << ret << endl;
}
return 0;
}
Codeforces LATOKEN Round 1 (Div. 1 + Div. 2)
https://www.dianhsu.com/2022/05/10/cf1534/