Tigerzhou的神奇序列

 2294: Tigerzhou的神奇序列

时间限制: C/C++ 1 s      Java/Python 3 s      内存限制: 128 MB      答案正确: 11      提交: 29
http://oj.jxust.edu.cn/problem?id=2294

题目描述

Give an array a with a length of n. If the sum in a subsequence is a multiple of M, then this sequence is called a "M sequence." Now you want to find the length of the longest subsequence for array a, which is the M sequence.

 

输入

The first behavior is two integers n, M, separated by spaces, and the second behavior is n integers, indicatinga[1]a[n]a[1]∼a[n], (1n105)(1≤n≤105), (1a[i]109,1n,M107)(1≤a[i]≤109,1≤n,M≤107)

 

输出

Output an integer to indicate the length of the longest subsequence kk

 

样例输入

7 5
10 3 4 2 2 9 8

样例输出

6



状态压缩dp
样例解释:
分别表示状态从0~4的每次的变化。

1 0 0 0 0
1 0 0 2 0 
1 0 3 2 2 
3 3 3 2 4 
3 5 4 4 4 
6 5 5 5 4 
6 6 5 7 6

当dp[last][j] != 0:

dp[last][(an[i] + j) % m] = max(dp[1 - last][(an[i] + j) % m], dp[1 - last][j] + 1);

 



 1 #include <bits/stdc++.h>
 2 #define N 100005
 3 using namespace std;
 4 
 5 int an[N];
 6 int dp[2][N*100];
 7 int n,m;
 8 int main(){
 9     cin>>n>>m;
10     for(int i = 1; i <= n; i++){
11         cin>>an[i];
12         an[i] = an[i] % m;
13     }
14     int last = 0;
15     dp[0][an[1]] = 1;
16     for(int i = 2; i <= n; i++){ //滚动数组 + 状态压缩
17         last = 1 - last;
18         for(int j = 0; j < m; j++){
19             if(dp[1 - last][j] != 0){
20                 dp[last][(an[i] + j) % m] = max(dp[1 - last][(an[i] + j) % m], dp[1 - last][j] + 1);
21             }else{
22                 dp[last][(an[i] + j) % m] = dp[1 - last][(an[i] + j) % m];
23             }
24         }
25     }
26     cout<<dp[last][0]<<endl;
27     return 0;
28 }

 

 
posted @ 2018-11-15 07:24  #忘乎所以#  阅读(185)  评论(0编辑  收藏  举报