Blue Bridge Cup 2017 Eighth C Language Group B Provincial Competition Exercise Problem Solution-Exercise Jk Times Interval

Daily Questions (92)

Lanqiao Cup 8th C Language Group B Provincial Competition Exercises

Exercise J: k times interval

Insert picture description here
Insert picture description here

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:
Insert picture description here

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;
}

I will continue to update afterwards. If you like my article, please remember to click three consecutive times, like and follow the collection. Every like and every attention you have will be an infinite motivation for me to move forward! ! ! ↖(▔▽▔)↗Thank you for your support!

Guess you like

Origin blog.csdn.net/qq_44631615/article/details/104762318