题解:洛谷 P15078 [ICPC 2024 Chengdu R] Expanding Array

题解:洛谷 P15078 [ICPC 2024 Chengdu R] Expanding Array

前言

简单数学题,可惜是小学生没时间参加考试,考试过后一下子就过了。

题意

给出一个整数数列 \(a\),可以执行以下操作:

选择两个相邻的整数 \(a_i\)、\(a_{i+1}\),要将 \(a_i \ \operatorname {and} \ a_{i+1}\)、\(a_i \ \operatorname {or} \ a_{i+1}\)、\(a_i \ \operatorname {xor} \ a_{i+1}\) 三个值中的一个插入到它们之间(可以执行该操作无数次)。

要求输出扩展后的数组中不同元素个数的最大值。

思路

经过暴力我们发现上述操作只与执行操作的两个数有关,不会牵扯到别的数,所以我们只用看相邻两个数的操作结果。

我们可以把所有的结果拆开,就会发现有这三个数很重要:

  • \(s1=a_i \ \operatorname {and} \ a_{i+1}\)。
  • \(s2= a_i \ \operatorname {and} \ (a_i \ \operatorname {xor} \ a_{i+1})\)。
  • \(s3=a_{a+1} \ \operatorname {and} \ (a_i \ \operatorname {xor} \ a_{i+1})\)。

其中 \(s1\) 为 \(a_i\) 和 \(a_{i+1}\) 共有的位,\(s2\) 为 \(a_i\) 独有的位,\(s3\) 为 \(a_{i+1}\) 独有的位。

因为位运算是在二进制的方法下进行的,所以我们不妨将 \(a_i\) 和 \(a_{i+1}\) 都转换位二进制数,就会发现答案只能由 \(s1\)、\(s2\) 和 \(s3\) 组成。

最终答案为:

  • \(0\)。
  • \(s1\)。
  • \(s2\)。
  • \(s3\)。
  • \(s1 \ \operatorname {and} \ s2\)。
  • \(s1 \ \operatorname {and} \ s3\)。
  • \(s2 \ \operatorname {and} \ s3\)。
  • \(s1 \ \operatorname {and} \ s2 \ \operatorname {and} \ s3\)。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,a[100005];
set<int> st;
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>n;
	st.insert(0);                                             //不要忘记记录0
	for(int i=1;i<=n;i--){                                    //输入顺序i++
		cin>>a[i];
		st.insert(a[i]);                                        //a[i]一定是其中一个值
	}
	for(int i=1;i<n;i++){                                     //不能记录到n,没有n+1位
		st.insert(a[i]&a[i+1]);                                 //记录a[i]和a[i+1]进行按位与运算的值
		st.insert(a[i]|a[i+1]);                                 //记录a[i]和a[i+1]进行按位或运算的值
		st.insert(a[i]^a[i+1]);                                 //记录a[i]和a[i+1]进行按位异或运算的值
		st.insert(a[i]^(a[i]&a[i+1]));                          //记录a[i]独有的位
		st.insert(a[i+1]^(a[i]&a[i+1]));                        //记录a[i+1]独有的位
	}
	cout<<st.size();
	return 0;
}

posted @ 2026-09-29 18:48  Loyal_Soldier_Ant  阅读(13)  评论(0)    收藏  举报
🖱️