You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indicesb1, b2, ..., bk (1 ≤ b1 < b2 < ... < bk ≤ n) in such a way that the value of is maximized. Chosen sequence can be empty.
Print the maximum possible value of .
The first line contains two integers n and m (1 ≤ n ≤ 35, 1 ≤ m ≤ 109).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Print the maximum possible value of .
4 4 5 2 4 1
3
3 20 199 41 299
19
In the first example you can choose a sequence b = {1, 2}, so the sum is equal to 7 (and that's 3 after taking it modulo 4).
In the second example you can choose a sequence b = {3}.
转自题解:
Let's consider the naive solution in O(2n) or O(2n·n). Iterate over all subsets of original set, calculate sums and take maximum of them modulo m.
Now we can use meet-in-the-middle technique to optimize it to . Preprocess the first elements naively and push sums modulo m to some array. After this process the second half with following algorithm.
Take sum of the set and find the greatest total sum of current and some sum in the array. As any sum of two numbers less than m can go no greater than 2m, we can consider just two values: the greatest number in array and the greatest number less thanm - currentSum in the array. This can be found by binary search over sorted array.
Overall complexity: .
参考代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,a,n) for(int i=(a);i<(n);++i)
#define per(i,a,n) for(int i=(n-1);i>=(a);--i)
#define pb push_back
const int Inf=1e9;
#define N 1000010
#define M 26
void dfs(int *a,int i,int n,int tot,vector<int>&sum,int mod){
if(i>=n){
cout<<tot<<' ';
sum.pb(tot);return ;
}
dfs(a,i+1,n,(tot+a[i])%mod,sum,mod);
dfs(a,i+1,n,tot,sum,mod);
}
int main(){
ios::sync_with_stdio(0);
int n,m;
int a[100];
while(cin>>n>>m){
vector<int>sum1,sum2;
rep(i,0,n) cin>>a[i],a[i]%=m;
dfs(a,0,n/2,0,sum1,m);
dfs(a,n/2,n,0,sum2,m);
sort(sum1.begin(),sum1.end());
sort(sum2.begin(),sum2.end());
int ans=0;
for(auto &i:sum1){
int x=m-i-1;
auto it=upper_bound(sum2.begin(),sum2.end(),x);
--it;
ans=max(ans,i+*it);
}
cout<<ans<<endl;
}
return 0;
}