Blue Bridge Cup test questions previous test questions k times interval (Java solution)
This question is adapted from the blog post of the boss, worship the boss!
topic
Given a sequence of length N, A1, A2,… AN, if the sum of a continuous subsequence Ai, Ai+1,… Aj (i <= j) is a multiple of K, we call this interval [ i, j] is the K times interval.
Can you find the total number of K-fold intervals in the sequence?
enter
The first line contains two integers N and K. (1 <= N, K <= 100000)
Each of the following N lines contains an integer Ai. (1 <= Ai <= 100000)
Output
Output an integer, representing the number of K times interval.
Ideas
Read in and process;
Suppose the sum of all the numbers before j (including j) is sum[j];
since the K times interval satisfies (sum[j]-sum[i-1])%k=0;
deformed sum[j]%k =sum [i-1]%k;
That is, you only need to find out how much before the current position is equal to your own sum%k;
calculate sum%k each time, and find how many remainders are the same before adding up, but There is also a lack of one case, that is, the case of sum%k = 0, which can form a K times interval from 0 to here;
Since the remainder of k is taken, the remainder will not exceed k, and only need to apply for k space storage;
the time complexity of this algorithm is o(n);
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n,k,sum = 0;
long count = 0;
n = sc.nextInt();
k = sc.nextInt();
int[] cnt = new int[k];
for (int i = 0; i < n; i++) {
sum = (sum + sc.nextInt()) % k;
count += cnt[sum]++;
}
count += cnt[0];
System.out.println(count);
sc.close();
}
}