codeforce 888E

qkoqhh發表於2017-11-10

EDU的題目就是水啊,這次A了5題,算是目前最多的一次吧。。

然後E還是有些經典的。。2分+dfs再合併,這種題雖然以前是見過很多次卻沒有去實現過,所以把自己的程式碼貼一下

合併的時候先排序再二分能夠有效地降低複雜度

//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define _link(x) for(edge *j=_h[x];j;j=j->next)
#define mem(a) memset(a,0,sizeof(a))
#define inf 1e9
#define ll long long
#define succ(x) (1<<x)
#define lowbit(x) (x&(-x))
#define NM 1000005
using namespace std;
int read(){
	ll x=0,f=1;char ch=getchar();
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
	return x*f;
}

int n,m,a[NM],b[NM],c[NM],d[NM],tot,k,v,ans;
ll s;
void dfs(int x){
	if(x==tot+1){
		c[++k]=s%m;
		return;
	}
	s+=b[x];dfs(x+1);
	s-=b[x];dfs(x+1);
}
int main(){
//	freopen("data.in","r",stdin);
	n=read();m=read();
	inc(i,1,n)a[i]=read()%m;
	inc(i,1,n/2)b[i]=a[i];
	tot=n/2;
	dfs(1);
	inc(i,1,k)d[i]=c[i];
	v=k;k=0;
	inc(i,n/2+1,n)b[i-n/2]=a[i];
	tot=n-n/2;mem(c);
	dfs(1);
	sort(d+1,d+1+v);
	inc(i,1,k)if(c[i]<m){
		int t=lower_bound(d+1,d+v,m-c[i]-1)-d;
		while(c[i]+d[t]>=m)t--;
		ans=max(ans,c[i]+d[t]);
	}
	printf("%d\n",ans);
	return 0;
}
E. Maximum Subsequence
time limit per test:1 second
memory limit per test:256 megabytes

You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, 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 .

Input

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).

Output

Print the maximum possible value of .

Examples
Input
4 4
5 2 4 1
Output
3
Input
3 20
199 41 299
Output
19
Note

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}.