题意
传送门 Codeforces 1582F2 Korney Korneevich and XOR (hard version)
题解
比较直接的想法是动态规划。 d p [ i ] [ j ] dp[i][j] dp[i][j] 代表 [ 0 , i ) [0,i) [0,i) 中子序列异或和为 i i i 时,序列末尾元素的最小值。顺序遍历元素,对每个元素枚举异或和可能的值,判断加入当前元素后是否满足子序列的单调递增性即可。总时间复杂度 O ( N × max { a i } ) O(N\times\max\{a_i\}) O(N×max{ai})。显然难以胜任,需要进一步优化。
元素值域较小,子序列异或和值域较小,对于值为 x x x 的元素,以其为末尾元素的子序列(不包括 x x x)的异或和为 y y y,这样的 ( x , y ) (x,y) (x,y),只有 ( max { a i } ) 2 (\max\{a_i\})^2 (max{ai})2 种可能。令 z = x ⊕ y z=x\oplus y z=x⊕y,那么值属于 [ x + 1 , max { a i } ] [x+1,\max\{a_i\}] [x+1,max{ai}] 的所有元素,都可以置于以 x x x 为末尾元素的子序列之后,那么将 z z z 传递至 [ x + 1 , max { a i } ] [x+1,\max\{a_i\}] [x+1,max{ai}]。暴力处理这样的传递过程,总时间复杂度 O ( ( max { a i } ) 3 ) O((\max\{a_i\})^3) O((max{ai})3)。
维护 r e c [ x ] rec[x] rec[x],其代表末尾元素小于 x x x 的子序列所能构成的异或和 y y y 的集合;对于不同的 y y y,应只与 x x x 异或一次。由于 x ⊕ y x\oplus y x⊕y 向 r e c [ x + 1 ] ⋯ r e c [ max { a i } ] rec[x+1]\cdots rec[\max\{a_i\}] rec[x+1]⋯rec[max{ai}] 传递时,满足右侧的单调性;即,若某个元素已传递了值,那么值大于其的元素一定也被传递了相同的值。那么可以维护一个指针 p t r [ z ] ptr[z] ptr[z],代表值 z z z 已传递的最小元素,此时可以避免同一个值被传递多次。总时间复杂度 O ( N + ( max { a i } ) 2 ) O(N+(\max\{a_i\})^2) O(N+(max{ai})2)。
#include <bits/stdc++.h>
using namespace std;
#define rep(i, l, r) for (int i = l, _ = r; i < _; ++i)
const int MAX_N = 1000005, MAX_A = 5005, MAX_X = 1 << 13;
int N, A[MAX_N], ptr[MAX_X];
vector<int> rec[MAX_A];
bool used[MAX_X];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
rep(i, 0, N) cin >> A[i];
rep(i, 0, MAX_A) rec[i].push_back(0);
rep(i, 0, MAX_X) ptr[i] = MAX_A;
memset(used, 0, sizeof(used));
used[0] = 1;
rep(i, 0, N)
{
for (auto &x : rec[A[i]])
{
int y = x ^ A[i];
used[y] = 1;
while (A[i] + 1 < ptr[y])
{
--ptr[y];
rec[ptr[y]].push_back(y);
}
}
rec[A[i]].clear();
}
vector<int> res;
rep(i, 0, MAX_X) if (used[i]) res.push_back(i);
cout << (int)res.size() << '\n';
for (auto &x : res)
cout << x << ' ';
cout << '\n';
return 0;
}