sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 2530 Accepted Submission(s): 966
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
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.
For each test case, there are two lines:
1.The first line contains two positive integers n, m (
2.The second line contains n positive integers x (
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
YES NO
问题链接:HDU5776 sum。
题意简述:(略)
问题分析:
这是一个连续子段和能否被整除的问题。
连续子段和可以由前缀和的差得到,所有将问题转换为求前缀和的问题。
即使得到前缀和,求两个前缀和的差(子段和)其计算复杂度为O(n*n),也是比较难以接受的。
对所有前缀和模除m,得到其余数放在数组中,如果有两个以上相同的余数,说明子段和能够被m整除。
由于最大的m比较小(1<=m<=5000),所有时间复杂度上看还是比较快的。
原始数据和前缀和是没有必要存储的,只需要存储前缀和的余数的计数就够用了,可以省去许多存储。
一种特殊的情况是,如果有前缀和除以m余数为0的话,说明存在连续的子段能够被m整除。这种情形,程序中需要做特殊的处理。
程序说明:(略)
AC的C++语言程序如下:
/* HDU5776 sum */ #include <iostream> #include <string.h> using namespace std; const int M = 5000; int prefixsum, remainder[M]; int main() { int t, n, m, a; cin >> t; while(t--) { cin >> n >> m; memset(remainder, 0, sizeof(remainder)); prefixsum = 0; remainder[0] = 1; for(int i=1; i<=n; i++) { cin >> a; prefixsum += a; prefixsum %= m; remainder[prefixsum]++; } bool flag = false; for(int i=0; i<m; i++) if(remainder[i] >= 2) { flag = true; break; } cout << (flag ? "YES" : "NO") << endl; } return 0; }