1230. K倍区间 前缀和

给定一个长度为 N 的数列,A1,A2,…AN,如果其中一段连续的子序列 Ai,Ai+1,…Aj 之和是 K 的倍数,我们就称这个区间 [i,j] 是 K 倍区间。

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

输入格式
第一行包含两个整数 N 和 K。

以下 N 行每行包含一个整数 Ai。

输出格式
输出一个整数,代表 K 倍区间的数目。

数据范围
1≤N,K≤100000,
1≤Ai≤100000
输入样例:
5 2
1
2
3
4
5
输出样例:
6

先使用前缀和处理,然后又题意知,要找的是s[r]-s[l-1]是k的倍数,即两个对k同余,因此记录每个s[i]的对k的余数,同余的两两组合:组合数:Cm2=Am2/A22 =m(m-1)/2 m为某个余数对应s[i]的个数

余数对应的个数需要用映射来存,映射实现用数组,用map都行,这里的数据范围用数组比较好

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main
{
	static int n,k;
	static long a[]=new long [100005],s[]=new long [100005],ans;
	static Map<Long,Integer> map=new HashMap<Long, Integer>();
	public static void main(String args[]) throws IOException
	{
		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
		String []ss;
		ss=in.readLine().split(" ");
		n=Integer.valueOf(ss[0]);
		k=Integer.valueOf(ss[1]);
		map.put(0l, 1);
		for(int i=1;i<=n;++i){
			a[i]=Integer.parseInt(in.readLine());
			s[i]=s[i-1]+a[i]; 
			s[i]%=k;
			if(map.containsKey(s[i])==false)map.put(s[i], 0);
			int cnt=map.get(s[i]);
			map.put(s[i], cnt+1);
		}
		for(Map.Entry<Long, Integer>entry :map.entrySet())
		{
			long t=entry.getValue();
			t*=(t-1);
			t/=2;
			ans+=t;
		}
		System.out.println(ans);
	}
}
posted @ 2022-11-17 23:02  林动  阅读(5)  评论(0编辑  收藏  举报