C3. Encryption (hard)+dp

C3. Encryption (hard)
time limit per test
2.2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

Heidi is now just one code away from breaking the encryption of the Death Star plans. The screen that should be presenting her with the description of the next code looks almost like the previous one, though who would have thought that the evil Empire engineers would fill this small screen with several million digits! It is just ridiculous to think that anyone would read them all...

Heidi is once again given a sequence A and two integers k and p. She needs to find out what the encryption key S is.

Let X be a sequence of integers, and p a positive integer. We define the score of X to be the sum of the elements of X modulo p.

Heidi is given a sequence A that consists of N integers, and also given integers k and p. Her goal is to split A into k parts such that:

  • Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
  • No two parts overlap.
  • The total sum S of the scores of those parts is minimized (not maximized!).

Output the sum S, which is the encryption code.

Input

The first line of the input contains three space-separated integers N, k and p (k ≤ N ≤ 500 000, 2 ≤ k ≤ 100, 2 ≤ p ≤ 100) – the number of elements in A, the number of parts A should be split into, and the modulo for computing scores, respectively.

The second line contains N space-separated integers that are the elements of A. Each integer is from the interval [1, 1 000 000].

Output

Output the number S as described in the problem statement.

Examples
Input
Copy
4 3 10
3 4 7 2
Output
Copy
6
Input
Copy
10 5 12
16 3 24 13 9 8 7 5 12 12
Output
Copy
13
Note

In the first example, if the input sequence is split as (3), (4, 7), (2), the total score would be . It is easy to see that this score is the smallest possible.

In the second example, one possible way to obtain score 13 is to make the following split: (16, 3), (24), (13), (9, 8), (7, 5, 12, 12).

第j步,x归那边

#include<cstdio>
#include<algorithm>
using namespace std;
#define maxk 105
int n,f[maxk],ma[maxk];
int main(){
	int k,p,x;scanf("%d%d%d",&n,&k,&p);
	f[0]=1000;
	for(int i=1;i<=n;i++){
		scanf("%d",&x);x%=p;
		for(int j=min(k,i);j>0;j--){
			if(j==i){
				f[j]=(j-1?f[j-1]:0)+x;ma[j]=x;continue;
			}
			int a=f[j]+x,b=f[j-1]+x;
			if(ma[j]+x>=p)a-=p;
			if(a<b)f[j]=a,(ma[j]+=x)%=p;
			else if(a==b)f[j]=a,ma[j]=max((ma[j]+x)%p,x);
			else f[j]=b,ma[j]=x;
		}
		if(i==n)printf("%d",f[k]);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值