题解:序列合并

洛谷P10512

Posted by TH911 on January 18, 2025

题目传送门

题意分析

给定 $a_1,a_2,a_3,\cdots,a_n$,要求将相邻两项 $a_i,a_{i+1}$ 合并为 $a_i\ \vert \ a_{i+1}$,合并 $k$ 次。

求最后 $a_1\ \&\ a_2\ \&\ a_3\ \&\ \cdots\ \&\ a_{n-k}$ 的最大值。

显然,最后的每一个 $a_i$ 都代表着一个区间 $a[l_i,r_i]$,有:

\[a_i=a_{l_i}\ \vert\ a_{l_i+1}\ \vert\ a_{l_i+2}\ \vert\ \cdots\ \vert\ a_{r_i}\]

一个显然成立的贪心思路:优先满足高位

因此我们可以使用倍增来枚举答案。

而检查答案正确性的函数内容也很简单,我们直接尝试去找不合并能够与出当前答案 $ans$ 的段数 $cnt$,判断 $k+cnt$ 是否大于 $n$ 即可。是则代表可以,否则不可以。

时间复杂度:$\mathcal O(n\log n)$。(严格意义上来说,是 $\mathcal O(30n)=O(n)$……)

AC 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath> 
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
const int N=2e5;
int n,k,a[N+1];
bool check(int ans){
	int pl=0,cnt=0;
	for(int i=1;i<=n;i++){
		pl|=a[i];
		if((pl&ans)==ans){
			pl=0;
			cnt++;
		}
	}return k+cnt>=n;
}
int main(){
	/*freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);*/
	
	scanf("%d %d",&n,&k);
	for(int i=1;i<=n;i++){
		scanf("%d",a+i);
	}
	int ans=0;
	for(int i=29;i>=0;i--){
		if(check(ans+(1<<i)))ans+=(1<<i);
	}printf("%d\n",ans);
	
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}