HDU - 5776 http://acm.hdu.edu.cn/showproblem.php?pid=5776
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
今天其实是补cf题的时候看到有一种尺取法,有博客说这题可写,但是感觉挺奇怪的,然后最后发现数据好像有点问题? 我写的恰好==m 都能过。。
正解是用前缀和取模做的。
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
const int maxn = 1e5+10;
int d[maxn];
int vis[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
met(vis,0);
int n,m;
scanf("%d%d",&n,&m);
int flag = 0;
int sum = 0,prek;
for(int i = 0; i < n; i++)
{
scanf("%d",&d[i]);
sum += d[i];
prek = sum % m;
if(!vis[prek]) vis[prek] = 1;
else flag = 1;
if(prek == 0) flag = 1;//别忘记直接mod m == 0的情况,这直接就可以判断正确了
}
flag ? printf("YES\n") : printf("NO\n");
}
return 0;
}
蓝桥杯 K倍区间
和上题题目相似,但是这个是求K倍区间一共多少个
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 1e5+10;
int vis[maxn];
int main()
{
int n,k,d,prek,sum = 0,ans = 0;
scanf("%d%d",&n,&k);
for(int i = 1; i <= n ; i++)
{
scanf("%d",&d);
sum = (sum + d);
prek = sum%k;
ans += vis[prek];
vis[prek]++;
}
printf("%d\n",ans+vis[0]); //这个vis[0] 是表示刚好mod k == 0 的值,因为从开始到i也是一个区间。
return 0;
}