C++k times interval (prefix sum)

Given a sequence of length N, A1, A2,...AN, if the sum of one continuous subsequence Ai, Ai+1,...Aj is a multiple of K, we call this interval [i,j] K Times interval.
Can you find the total number of K-fold intervals in the sequence?
Input format The
first line contains two integers N and K.
Each of the following N lines contains an integer Ai.
Output format
Output an integer, representing the number of K times interval.
Data range
1≤N,K≤100000,1≤Ai≤100000
Input example:
5 2
1
2
3
4
5
Output example:
6

AC code:

#include<stdio.h>

int n,k;
long long s[100010];
int m[100010];
long long ans;

int main()
{
    
    
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;++i)//求前缀和
    {
    
    
        scanf("%lld",&s[i]);
        s[i]+=s[i-1];
    }
    m[0]=1;//s[0]模k为0
    for(int i=1;i<=n;++i)//区间右端点r固定为i,讨论左端点l
    {
    
    
        //只要s[r]和s[l]模k相同,[l+1,r]必为k倍区间
        //找到在s[r]之前的所有满足条件的s[l]即可
        ans+=m[s[i]%k];
        ++m[s[i]%k];
    }
    printf("%lld",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108817791