Codeforces-981D:Bookshelves(思维+DP)

D. Bookshelves
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 kk bookshelves. He decided that the beauty of the kk shelves is the bitwise AND 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 kk 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 nn and kk (1kn501≤k≤n≤50) — the number of books and the number of shelves in the new office.

The second line contains nn integers a1,a2,ana1,a2,…an, (0<ai<2500<ai<250) — the prices of the books in the order they stand on the old shelf.

Output

Print the maximum possible beauty of kk shelves in the new office.

Examples
input
Copy
10 4
9 14 28 1 7 13 15 29 2 31
output
Copy
24
input
Copy
7 3
3 14 15 92 65 35 89
output
Copy
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.

In the second example you can split the books as follows:

(3+14+15+92)&(65)&(35+89)=64.


思路:因为答案要尽量大,而DP又不能直接求得答案。考虑贪心,即从二进制的高位开始向低位枚举,假设当前位为i,答案为ans,那么去检测当前的ans|(1<<i)能否得到,若能得到,那么ans|=1<<i;否则继续枚举i。检测的时候用DP就可以了。即d[i][j]表示[1,i]分为j段时,每段价值的二进制表示中是否包含1<<x

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e6+10;
const int MOD=1e9+7;
const double PI=acos(-1.0);
typedef long long ll;
ll sum[51],d[51][51];
int k,n;
ll check(ll x)
{
    memset(d,0,sizeof d);
    for(int i=1;i<=n;i++)
    {
        if((sum[i]&x)==x)d[i][1]=1;
        for(int j=1;j<i;j++)
        {
            if(((sum[i]-sum[j])&x)!=x)continue;
            for(int h=2;h<=min(k,i);h++)d[i][h]|=d[j][h-1];
        }
    }
    return d[n][k];
}
int main()
{
    cin>>n>>k;
    for(int i=1;i<=n;i++)scanf("%lld",&sum[i]),sum[i]+=sum[i-1];
    ll ans=0;
    for(int i=60;i>=0;i--)
    {
        if(check(ans|(1ll<<i)))ans|=1ll<<i;
    }
    cout<<ans<<endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/mitsuha_/article/details/80481081