题意:给定数组与常数k,判断有多少个区间满足a[l~r]的和是k的倍数。
分析:暴力遍历时间复杂度为O(n^3)肯定会超时,利用前缀和进行优化后时间复杂度为O(n^2),也是通过不了。
计算前缀和 (s[r]-s[l-1])%k==0 s[r]%k==s[l-1]%k,这样就有了解题的思路。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;
int n,k;
ll a[maxn];
ll s[maxn];
ll c[maxn];
int main()
{
ll res=0;
scanf("%d%d",&n,&k);
c[0]=1;//s[0]%k==0
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&a[i]);
s[i]=s[i-1]+a[i];
res+=c[s[i]%k];
c[s[i]%k]++;
}
printf("%lld\n",res);
return 0;
}