1230. K倍区间

题目链接

1230. K倍区间

给定一个长度为 \(N\) 的数列,\(A_1,A_2,…A_N\),如果其中一段连续的子序列 \(A_i,A_{i+1},…A_j\) 之和是 \(K\) 的倍数,我们就称这个区间 \([i,j]\)\(K\) 倍区间。

你能求出数列中总共有多少个 \(K\) 倍区间吗?

输入格式

第一行包含两个整数 \(N\)\(K\)

以下 \(N\) 行每行包含一个整数 \(A_i\)

输出格式

输出一个整数,代表 \(K\) 倍区间的数目。

数据范围

\(1≤N,K≤100000,\)
\(1≤A_i≤100000\)

输入样例:

5 2
1
2
3
4
5

输出样例:

6

解题思路

前缀和

求出前缀和 \(s\),则区间 \([l,r]\) 的和为 \(s[r]-s[l-1]\),为使 \((s[r]-s[l-1])\%k=0\),则 \(s[r]\%k=s[l-1]\%k\),固定 \(r\),统计前面值为 \(s[r]\%\) 的数量,注意这里 \(l-1\) 的范围为 \([0,r-1]\),而前缀和对于 \(0\) 的情况值为 \(0\),所以开始需要初始化 \(cnt[0]=1\)

  • 时间复杂度:\(O(n)\)

代码

// Problem: K倍区间
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1232/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e5+5;
int n,k,a[N],s[N],cnt[N];
int main()
{
    cin>>n>>k;
    for(int i=1;i<=n;i++)
    {
    	cin>>a[i];
    	s[i]=(a[i]+s[i-1])%k;
    }
    LL res=0;
    cnt[0]=1;
	for(int i=1;i<=n;i++)
	{
		res+=cnt[s[i]];
		cnt[s[i]]++;
	}    
	cout<<res;
    return 0;
}
posted @ 2022-02-22 14:08  zyy2001  阅读(87)  评论(1编辑  收藏  举报