题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6794
Problem Description
Tokitsukaze has a sequence of length n, denoted by a.
Tokitsukaze can merge two consecutive elements of a as many times as she wants. After each operation, a new element that equals to the sum of the two old elements will replace them, and thus the length of a will be reduced by 1.
Tokitsukaze wants to know the maximum possible number of elements that are multiples of p she can get after doing some operations (or doing nothing) on the sequence a.
Input
There are several test cases.
The first line contains an integer T (1≤T≤20), denoting the number of test cases. Then follow all the test cases.
For each test case, the first line contains two integers n and p (1≤n,p≤105), denoting the length of the sequence and the special number, respectively.
The second line contains n integers, where the i-th integer ai (1≤ai≤105) is the i-th element of a.
It is guaranteed that the sum of n in all test cases is no larger than 106.
Output
For each test case, output in one line the maximum possible number of elements that are multiples of p after doing some operations.
Sample Input
2
5 3
2 1 3 2 1
3 1
123 456 789
Sample Output
3
3
翻译:
给定两个数n和p,接下来是长度为n的序列。每次可以把序列相邻的两个数合并为两个数的和,数组的长度减1。求数组中是p的倍数的数最多有多少个。
代码:
#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int main()
{
int t,n,p;
int a[N];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&p);
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
int pos=1;
int sum=0,res=0;
for(int i=1; i<=n; i++)
{
sum+=a[i];
if(sum%p==0)
{
sum=0;
res++;
pos=i+1;
}
else///匹配不成功
{
int ta=sum;///不在原来的sum和pos上进行操作,因为可能不匹配
int lo=pos;
while(i>lo)
{
ta-=a[lo++];
if(ta%p==0)
{
res++;
sum=0;
pos=i+1;
break;
}
}
}
}
printf("%d\n",res);
}
return 0;
}