D. Bookshelves
Mr Keks is a typical white-collar in Byteland.
He has a bookshelf in his office with some books on it, each book has an integer positive price.
Mr Keks defines the value of a shelf as the sum of books prices on it.
Miraculously, Mr Keks was promoted and now he is moving into a new office.
He learned that in the new office he will have not a single bookshelf, but exactly kkk bookshelves. He decided that the beauty of the ? shelves is the bitwise ANDANDAND of the values of all the shelves.
He also decided that he won’t spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on ? shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
Input
The first line contains two integers nnn and kkk (1≤k≤n≤50)(1≤k≤n≤50)(1≤k≤n≤50) — the number of books and the number of shelves in the new office.
The second line contains ? integers a1,a2,…an,(0<ai<250)a_1,a_2,…a_n, (0<a_i<250)a1,a2,…an,(0<ai<250) — the prices of the books in the order they stand on the old shelf.
Output
Print the maximum possible beauty of kkk shelves in the new office.
Examples
input
10 4
9 14 28 1 7 13 15 29 2 31
output
24
input
7 3
3 14 15 92 65 35 89
output
64
Note
In the first example you can split the books as follows:
(9+14+28+1+7)&(13+15)&(29+2)&(31)=24(9+14+28+1+7)\&(13+15)\&(29+2)\&(31)=24(9+14+28+1+7)&(13+15)&(29+2)&(31)=24.
In the second example you can split the books as follows:
(3+14+15+92)&(65)&(35+89)=64(3+14+15+92)\&(65)\&(35+89)=64(3+14+15+92)&(65)&(35+89)=64.
-
题意
- 就是求把一个序列分成若干个连续子序列,使得这些子序列的元素和按位与起来最大
-
解法
- 看的tutorialtutorialtutorial,感觉挺有道理的233
- 从高位到低位能选就选,那么对于给定的数如何判断能不能选呢?显然写个简单的dp就行了,定义dp[i][j]表示是否能把前i个数分成j段连续子序列使得元素和按位与起来能得到这个需要判断的数,然后注意的是后来判断的时候需要带上前面已经取到的位,不然你每次取的分段不一定都相同,导致结果可能偏大
-
附代码:
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=55; int n,k;ll a[maxn],ans=0,sum[maxn]; bool dp[maxn][maxn]; bool check(ll cur) { memset(dp,false,sizeof(dp)); dp[0][0]=true; for(int i=1;i<=n;i++){ for(int j=1;j<=k;j++){ for(int l=1;l<=i;l++) { if((cur&(sum[i]-sum[l-1]))==cur) dp[i][j]|=dp[l-1][j-1]; } } } return dp[n][k]; } int main() { scanf("%d %d",&n,&k); for(int i=1;i<=n;i++) scanf("%lld",&a[i]),sum[i]=sum[i-1]+a[i]; for(int i=55;i>=0;i--) if(check(ans|(1LL<<i))) ans|=(1LL<<i); printf("%lld\n",ans); }