跳到正文

个人记录

12.5周五训练课总结

hqj_约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年12月8日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

T705935 异或前缀和三 (three)

这道题首先我们可以求出前缀异或和sum,然后用一个数组求出所有区间的异或和和长度,接着在按异或和从⼩到⼤排序,如果相同那么长度小的在前。

然后我们可以再建一个数组last,用来记录每个位置之后的最小长度,最后用二分求出第一个大于等于 x 的位置。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3005;
const int M = 3000 * 3001 / 2 + 5;
struct node {
    int sum, len;
} s[M];

int n, a[N], sum[N], last[M], m, k;

int cmp(node a1, node a2) {
    if (a1.sum != a2.sum)
        return a1.sum < a2.sum;
    return a1.len < a2.len;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        sum[i] = sum[i - 1] ^ a[i];//前缀异或和
    }

    k = 0;
    for (int i = 1; i <= n; i++) {//记录异或和和长度
        for (int j = i; j <= n; j++) {
            s[++k] = {sum[j] ^ sum[i - 1], j - i + 1};
        }
    }

    sort(s + 1, s + 1 + k, cmp);

    last[k + 1] = INT_MAX;
    for (int i = k; i >= 1; i--) {
        last[i] = min(s[i].len, last[i + 1]);
    }

    while (m--) {
        int x;
        cin >> x;

        int l = 1, r = k, pos = k + 1;
        while (l <= r) {//二分
            int mid = (l + r) / 2;
            if (s[mid].sum >= x) {
                pos = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }

        if (pos == k + 1) {
            cout << "-1" << endl;
        } else {
            cout << last[pos] << endl;
        }
    }

    return 0;
}

T706328 异或前缀和四 (four)

这道题我们也可以先求出前缀异或和,然后再用桶数组记录前缀异或值出现的次数和出现的位置,最后输出答案即可。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+5;
int n,a[N],sum[N],ans;
map<int,int> cnt,mp;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		sum[i]=sum[i-1]^a[i];////前缀异或和
	}
	cnt[0] = 1;
	mp[0] = 0;
	for(int k=1;k<=n;k++){
		int v=sum[k];
		ans+=cnt[v]*(k-1)-mp[v];
		cnt[v]++;
		mp[v]+=k;
	}
	cout<<ans;
	return 0;
}
原文