CF - 665E 字典树

题意:

给出一串长度为n的序列,找到有多少个子串的异或和 ≥ k。

思路:

字典树的套路,因为异或和满足前缀和性质,所以[l,r]区间内的a[i]的异或和就可以表示为sum[r]^sum[l-1],这样构造一个sum的字典树。
每次用sum[i]在字典树上爬,同时与k进行每一位的比较,一定要保证sum[i]和它爬的字典树的路径的异或和要≥k,所以异或和的每一位都要≥k的每一位。故分为四种情况讨论即可,具体细节看代码。

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 10;
const int maxbit = 33;

struct node {
	node *Next[2];
	ll cnt;
};

struct Trie {
	node *root;

	void init() {
		root = new node;
		root->Next[0] = root->Next[1] = NULL;
	}

	void ins(ll x) {
		node *p = root;
		for (int i = maxbit; i >= 0; i--) {
			int id = (x & (1LL << i)) ? 1 : 0;
			if (p->Next[id] == NULL) {
				node *q = new node;
				for (int j = 0; j < 2; j++) q->Next[j] = NULL;
				p->Next[id] = q;
				p = p->Next[id];
				p->cnt = 1;
			}
			else {
				p = p->Next[id];
				p->cnt++;
			}
		}
	}

	ll dfs(node *p, ll x, ll k, int deep) {
		if (p == NULL) return 0;
		if (deep == -1) return p->cnt;
		int bx = (x & (1LL << deep)) ? 1 : 0, bk = (k & (1LL << deep)) ? 1 : 0;
		ll res = 0;
		if (bx == 1 && bk == 1) {
			res += dfs(p->Next[0], x, k, deep - 1);
		}
		else if (bx == 1 && bk == 0) {
			res += dfs(p->Next[1], x, k, deep - 1) + ((p->Next[0] != NULL) ? p->Next[0]->cnt : 0);
		}
		else if (bx == 0 && bk == 1) {
			res += dfs(p->Next[1], x, k, deep - 1);
		}
		else {
			res += dfs(p->Next[0], x, k, deep - 1) + ((p->Next[1] != NULL) ? p->Next[1]->cnt : 0);
		}
		return res;
	}

} trie;

ll sum[MAXN];

int main() {
    //freopen("in.txt", "r", stdin);
	int n, k;
	scanf("%d%d", &n, &k);
	for (int i = 1; i <= n; i++){
		scanf("%I64d", &sum[i]);
		sum[i] ^= sum[i - 1];
	}
	ll ans = 0;
	trie.init();
	trie.ins(0);
	for (int i = 1; i <= n; i++) {
		ll tmp = trie.dfs(trie.root, sum[i], k, maxbit);
		//cout << tmp << endl;
		ans += tmp;
		trie.ins(sum[i]);
	}
	printf("%I64d\n", ans);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值