[洛谷刷题-C++]P3131-Subsequences Summing to Sevens S

problem

Difficulty: Popularity-

Description:

https://www.luogu.com.cn/problem/P3131

Enter an array and find the longest substring whose sum is divisible by 7.

Input range:

Input length: 1≤N≤50,000

Input number size: 0…1,000,000

Enter the case:

7
3
5
1
6
2
14
10

My code:

Comparing math questions, if it is directly violent, n! Time complexity, even if it is level by level sum[i] = sum[i-1] + N, and then% 7, it is concluded that the longest time complexity is n^2, If it still doesn't work, it becomes a math problem:

Thinking of the solution of two sum, we can compare the length of the interval sum divisible by 7:

The interval M includes N and X, ΣM = ΣN + ΣX, and

ΣM % 7 = 1,ΣN % 7 = 1

ΣM % 7 - ΣN % 7 = 0

(ΣM - ΣN) % 7 = 0

ΣX% 7 = 0 ——————> From the large interval M, if you find an interval N in it, then subtract the two to get the interval X that is divisible by 7. If N is as small as possible, you get X is the longest interval divisible by 7, then to get X, get N first, which is to get the end position of M and the start position of N. (ΣM% 7 = ΣN% 7, where the remainder of both to 7 is the same)

On c++

#include <iostream>
using namespace std;

int num, temp, res = 0, be[8], en[8], sum[50001];

int main() {
	cin >> num;
	for (int i = num; i-- > 0;) { // 从尾到头获取逐个区间的和并求余(自动形成了所有同结尾的最大区间)
		cin >> temp;
		sum[i] = (temp + sum[i + 1]) % 7;
	}
	for (int i = num; i-- > 0;) // 然后得出相应的开始结束位置
		if (en[sum[i]]) be[sum[i]] = i; else en[sum[i]] = i;

	for (int i = 7; i-- > 0;) // 通过开始结束为止得出最大的区间
		if(be[i] && en[i]) res = max(res, en[i] - be[i]);

	cout << res;
}

 

 

 

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/110553039