hdu5776 sum
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.
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
Source
初试前缀和,对于求区间和很好用
关键代码:
//得到前缀和 for(int i = 1;i <= n;i++){ cin >> a[i]; sum[i] = sum[i - 1] + a[i]; }
这个题要求是否有个连续区间的和可以整除m
想到区间和,但又不能暴力求所有的区间和
对每个前缀和都对m求模,如果出现0,肯定可以;如果出现两个相同的数,也是可以(加上两个数中间的和正好一个轮回,说明中间的和可以整除m)。
#include<iostream> using namespace std; const int MAXN = 100000; int sum[MAXN + 2] = {0}; int a[MAXN + 2]; int main() { int T,n,m; cin >> T; while(T--){ int s[5002] = {0}; int flag = 0; cin >> n >> m; //得到前缀和 for(int i = 1;i <= n;i++){ cin >> a[i]; sum[i] = sum[i - 1] + a[i]; } //处理前缀和 for(int i = 1 ; i <= n;i++){ sum[i] %= m; s[sum[i]] += 1; //cout << sum[i] <<endl; if(sum[i] == 0){ flag = 1; break; } } for(int i = 0; i < 5002;i++){ if(s[i] > 1){ flag = 1; break; } } if(flag) cout << "YES" << endl; else cout << "NO" << endl; } // for(int i = 1 ; i <= N;i++){ // cout << sum[i] << endl; // } /* int l,r; int T; cin >> T; while(T--){ cin >> l >> r; cout << sum[r] - sum[l - 1] << endl; } */ return 0; }