sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 4549 Accepted Submission(s): 1586
Problem Description
Given a sequence, you're asked whether there exists a consecutive subsequence whose sum is divisible by m. output YES, otherwise output NO
Input
The first line of the input has an integer T (1≤T≤10), which represents the number of test cases.
For each test case, there are two lines:
1.The first line contains two positive integers n, m (1≤n≤100000, 1≤m≤5000).
2.The second line contains n positive integers x (1≤x≤100) according to the sequence.
Output
Output T lines, each line print a YES or NO.
Sample Input
2 3 3 1 2 3 5 7 6 6 6 6 6
Sample Output
YES NO
【题意】
给定一个序列,问是否存在一个和可被m整除的连续子序列。输出YES,否则输出NO
【思路】
1)如果有一个前缀和可以被m整除的,那么就找到一个满足条件的子序列了,这个子序列都是从第一个元素开始累加的;
2)如果从1开始的没有找到可被整除的,那就要找中间一段子序列,当有两个从1开始的子序列%m的值相等,那么他俩相减的值就可以被m整除
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
int a[5005],sum[maxn];
int main()
{
int n,m,x,t,y;
scanf("%d",&t);
while(t--)
{
mem(a);
mem(sum);
int flag = 0;
sum[0] = 0;
scanf("%d%d",&n,&m);
for(int i = 1; i <= n;i++)
{
scanf("%d",&x);
sum[i] = (sum[i-1] + x)%m;
a[sum[i]]++;
if(a[sum[i]] > 1 || sum[i] == 0)
flag = 1;
}
if(!flag)
puts("NO");
else
puts("YES");
}
return 0;
}