[Blue Bridge Cup 2017 Province B] k times interval
Given a sequence of length N, A1, A2,...AN, if the sum of a continuous subsequence Ai, Ai+1,...Aj is a multiple of K, we call this interval [i,j] K double interval.
Can you find out how many K-fold intervals there are 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-fold intervals.
data range
1≤N,K≤100000,
1≤Ai≤100000
Input sample:
5 2
1
2
3
4
5
Sample output:
6
The first method: three layers of violence cycle (timeout)
#include<iostream>
using namespace std;
int main()
{
int n, g[100010], i, j, k, sum = 0, ans = 0;
cin >> n >> k;
for (i = 1; i <= n; i++)
{
cin >> g[i];
}
for (i = 1; i <= n; i++)
{
for (j = i; j <= n; j++)
{
sum = 0;
for (int m = i; m <= j; m++)
{
sum += g[m];
}
if (sum % k == 0)
ans++;
}
}
cout << ans << endl;
return 0;
}
The second method: two layers of loop + prefix and (still timeout)
#include<iostream>
using namespace std;
int main()
{
int n, g[100010], s[100010]={0}, i, j, k, sum = 0, ans = 0;
cin >> n >> k;
for (i = 1; i <= n; i++)
{
cin >> g[i];
s[i] = s[i - 1] + g[i];
}
for (i = 1; i <= n; i++)
{
for (j = i; j <= n; j++)
{
int t = s[j] - s[i - 1];
if (t % k == 0)
ans++;
}
}
cout << ans << endl;
return 0;
}
The third method: one layer of loop + prefix sum (no timeout)
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
const int N = 100010;
int n, k;
ll s[N], cnt[N];
int main()
{
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++)
{
scanf("%lld", &s[i]);
s[i] += s[i - 1];
}
ll res = 0;
cnt[0] = 1;
for (int i = 1; i <= n; i++)
{
res += cnt[s[i] % k];
cnt[s[i] % k]++;
}
printf("%lld\n", res);
return 0;
}