Daily Questions (92)
Lanqiao Cup 8th C Language Group B Provincial Competition Exercises
Exercise J: k times interval
Prefix sum method
This method cannot get full marks for this question, because the data range of the question is large, and the prefix sum method cannot traverse so many orders of magnitude
C++ code:
#include<iostream>
using namespace std;
int main()
{
int n, k;
int a[100010];
int s[100010]; //前缀和
cin >> n >> k;
s[0] = 0;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = s[i - 1] + a[i];
}
long long ans = 0;
for(int i = 1; i <= n; i++)
{
for(int j = i; j < n; j++)
{
if((s[j] - s[i]) % k == 0)
{
ans++;
}
}
}
cout << ans << endl;
return 0;
}
Sample running results:
Mathematics
C++ code:
#include<iostream>
#include<map>
using namespace std;
int n, k;
int a[100010];
int s[100010];
map<int, int> cnt;
int main()
{
cin >> n >> k;
s[0] = 0;
cnt[0] = 1;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = (s[i - 1] + a[i]) % k;
cnt[s[i]]++;
}
long long ans = 0;
for(int i = 0; i < k; ++i)
{
ans += (long long)cnt[i] * (cnt[i] - 1) / 2;
}
cout << ans << endl;
return 0;
}