跳到正文

题解

题解:AT_abc390_d [ABC390D] Stone XOR

xiaoyin2011约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年1月26日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

AT_abc390_d [ABC390D] 石头异或 题解

题目链接

题目大意

给出 NN 袋石头,每袋 AiA_i 个。进行若干次合并操作后剩余的每袋石头数为 BB,此时分数为 B1⊕B2⊕⋯⊕BNB_1 \oplus B_2 \oplus \cdots \oplus B_N,问多少种不同的分数。

思路

N≤12N \le 12,大家都能看出来阶乘级算法不会超时,12!=479001600≈4.8×10812! = 479001600 \approx 4.8 \times 10^8。我意识到这是一个 DFS 题目,但是我的 DFS 方法是 1212≈9×101212^{12} \approx 9 \times 10^{12}。

所以为什么答案不会达到 121212^{12} 呢?这个问题困惑了我很久。我的方法是,对于每个袋子,选择它最后去到哪个袋子。显然复杂度达到 O(NN)O(N^N)。这个方法会选择出一些不可能实现的情况,比如 11 去了 22、22 去了 11,而只有这两个袋子是无法实现的。

所以为什么 12!12! 级别的算法能实现呢?对于从 11 开始决定归宿的袋子,第一个袋子进入第 22 组是可能产生重复的情况,因为有可能后面没有一个进入 11 组。

有一个数字叫做贝尔数(Bell Number),表示大小为 NN 的可重几何有多少种分配进入不限数量的组的方法。而 B(12)=4213597<5×106B(12) = 4213597 < 5 \times 10^6。

至于这道题 DFS 的实现,所有题解应该都说了。传递目前是哪一个袋子和已经有多少组,每次考虑分进以前的组或者新开一组,最后统计答案即可。

实现

虽然复杂度是在范围内,可是如果要得到分并不是很简单。首先需要使用 unordered_set 而不是 set,可以少一个 log⁡\log,这个不必多说。

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll N, A[15], g[15], sum[15], ans;
unordered_set<ll> st;
void dfs(ll now, ll gcnt)
{
	if (now == N + 1)
	{
		memset(sum, 0, sizeof(sum));
		ans = 0;
		for (int i = 1; i <= N; i++)
			sum[g[i]] += A[i];
		for (int i = 1; i <= gcnt; i++)
			ans ^= sum[i];
		st.insert(ans);
		return ;
	}
	for (int i = 1; i <= gcnt; i++)
	{
		g[now] = i;
		dfs(now + 1, gcnt);
	}
	g[now] = gcnt + 1;
	dfs(now + 1, gcnt + 1);
}
int main()
{
	scanf("%lld", &N);
	for (int i = 1; i <= N; i++)
		scanf("%lld", &A[i]);
	dfs(1, 1);
	printf("%lld\n", st.size()); 
	return 0;
}

上面是根据思路写出来的代码,gig_i 表示 ii 袋分入哪一组,sumisum_i 表示分配后 ii 组有多少石子,ansans 是答案。但是这个代码提交上去你会荣获 TLE,因为 12!12! 已经接近 5×1085 \times 10^8,如果我们达到 O(N×N!)O(N \times N!),就会 TLE。

因此我们考虑在修改 gig_i 的同时更新 sumisum_i 和 ansans。sumisum_i 很显然可以通过加减进行更新和回溯,ansans 则可以通过异或的性质——连续两次异或一个数字则会消去它,先异或原 sumisum_i,再异或新 sumisum_i 即可。这样,DFS 结尾我们只需要把 ansans 扔进 unordered_set 里。

AC Code

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll N, A[15], sum[15], ans;
unordered_set<ll> st;
void dfs(ll now, ll gcnt)
{
	if (now == N + 1)
	{
		st.insert(ans);
		return ;
	}
	for (int i = 1; i <= gcnt; i++)
	{
		ans ^= sum[i];
		sum[i] += A[now];
		ans ^= sum[i];
		dfs(now + 1, gcnt);
		ans ^= sum[i];
		sum[i] -= A[now];
		ans ^= sum[i];
	}
	sum[gcnt + 1] = A[now];
	ans ^= sum[gcnt + 1];
	dfs(now + 1, gcnt + 1);
	ans ^= sum[gcnt + 1];
	sum[gcnt + 1] = 0;
}
int main()
{
	scanf("%lld", &N);
	for (int i = 1; i <= N; i++)
		scanf("%lld", &A[i]);
	dfs(1, 1);
	printf("%lld\n", st.size()); 
	return 0;
}
原文