传送锚点:
[USACO16JAN]Subsequences Summing to Sevens S - 洛谷
题目描述
Farmer John's \(N\) cows are standing in a row, as they have a tendency to do from time to time. Each cow is labeled with a distinct integer ID number so FJ can tell them apart. FJ would like to take a photo of a contiguous group of cows but, due to a traumatic childhood incident involving the numbers \(1 \ldots 6\), he only wants to take a picture of a group of cows if their IDs add up to a multiple of 7.
Please help FJ determine the size of the largest group he can photograph.
给你n个数,分别是a[1],a[2],...,a[n]。求一个最长的区间[x,y],使得区间中的数(a[x],a[x+1],a[x+2],...,a[y-1],a[y])的和能被7整除。输出区间长度。若没有符合要求的区间,输出0。
输入格式
The first line of input contains \(N\) (\(1 \leq N \leq 50,000\)). The next \(N\)
lines each contain the \(N\) integer IDs of the cows (all are in the range
\(0 \ldots 1,000,000\)).
输出格式
Please output the number of cows in the largest consecutive group whose IDs sum
to a multiple of 7. If no such group exists, output 0.
样例 #1
样例输入 #1
7
3
5
1
6
2
14
10
样例输出 #1
5
提示
In this example, 5+1+6+2+14 = 28.
思路
这题结合前缀和和数学知识,我一开始的想法是算出前缀和存储到一个数组,使用二重循环求出最大能被余7的连续个数,但样例点有5万个,会超时
首先我们要对前缀和加上第i个数字都进行模7处理,然后用到一个小定理,若两个数相减 (mod 7=0) ,那么这两个数 mod 7 的余数一定相同!
然后我们回想一下我们是怎么求一维数组下的一段前缀和,是不是用sum[r] - sum[l - 1](sum为存储前缀和),所以我们引入l、r两个数组,数组大小都为7,
l[i]存%7为i的最小值l- 1,r[i]存%7为i的最大值r,-1代表没有%7为i的前缀和,注意l数组中第一个值初始化为0,因为当任意前缀和sum[x]%7等于0时,最长区间就是x
code
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int l[7], r[7];//余数
fill(l, l + 7, -1);
fill(r, r + 7, 0);
l[0] = 0;
int sum = 0;//前缀和
for (int i = 1; i <= n; ++i) {
int a;
cin >> a;
sum = (sum + a) % 7;
if (l[sum] == -1) l[sum] = i;
r[sum] = i;
}
int ans = 0;
for (int i = 0; i < 7; ++i) {
if (l[i] != -1) {
ans = max(r[i] - l[i], ans);
}
}
cout << ans;
return 0;
}
标签:Sevens,group,前缀,int,sum,Summing,Subsequences,数组,cows
From: https://www.cnblogs.com/6Luffy6/p/18326086