第四题:Tokitsukaze and Rescue
题目:
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.
思路
将前缀和的模数存进栈,如果栈内有两个数相等,那么就意味着这之间的数的和可以为p的倍数,那么我们就把这写数合并,因为合并了 前面的数也不能用了,所以就把栈清空,假设我们那个数模p为x,那么如果后面有个人膜了p之后等于x就证明这之间的也可以用。 所以我们要把x进栈。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int N=1e5+10;
ll a[N],sum[N];
int stk[N],top;
int main()
{
//freopen("test.in","r",stdin);//设置 cin scanf 这些输入流都从 test.in中读取
//freopen("test.out","w",stdout);//设置 cout printf 这些输出流都输出到 test.out里面去
//ios::sync_with_stdio(false);
//cin.tie(0),cout.tie(0);
int T;
cin>>T;
while(T--)
{
memset(stk,0,sizeof stk);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]),sum[i]=sum[i-1]+a[i];
top=0;
int ans=0;
stk[top++]=0;
for(int i=1;i<=n;i++)
{
stk[top++]=sum[i]%m;
for(int j=0;j<top-1;j++)
{
if(stk[j]==stk[top-1])
{
ans++;
stk[0]=stk[top-1];
top=1;
break;
}
}
}
cout<<ans<<endl;
}
return 0;
}