B. Modulo Sum
time limit per test
2 secondsmemory limit per test
256 megabytesinput
standard inputoutput
standard outputYou are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and the number such that sum should be divisible by it.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
Output
In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.
Examples
input
3 5
1 2 3
output
YES
input
1 6
5
output
NO
input
4 6
3 1 1 3
output
YES
input
6 6
5 5 5 5 5 5
output
YES
题意:从n个数中选取任意个数(最少一个)使得对m取模为0;
思路:首先当n>m的时候,是必定的;
根据抽屉原理,前缀和必定有两个相等的数;sl==sr;
sr-sl=0;意思就是[l,r]的和%m==0;
n<m时,利用01背包,复杂度n*m;
#include<bits/stdc++.h> using namespace std; #define ll __int64 #define mod 1000000007 #define pi (4*atan(1.0)) const int N=1e3+10,M=1e6+10,inf=1e9+10; int a[M]; int dp[N][N]; int max(int x,int y,int z) { return max(x,max(y,z)); } int main() { int x,y,z,i,t; memset(dp,0,sizeof(dp)); scanf("%d%d",&x,&y); for(i=0;i<x;i++) scanf("%d",&a[i]); if(x>y) { printf("YES "); return 0; } for(i=0;i<x;i++) dp[i][(a[i]%y)]=1; for(i=1;i<x;i++) { for(t=0;t<y;t++) { dp[i][t]=max(dp[i][t],dp[i-1][t]); dp[i][(t+a[i])%y]=max(dp[i-1][t],dp[i][(t+a[i])%y]); } } if(dp[x-1][0]) printf("YES "); else printf("NO "); return 0; }