一、题目描述
Farmer John's Ncows 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 , 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().
The next N lines each contain the N integer IDs of the cows
(all are in the range).
第一行是n(1<=n<=50000);
以后的n行是n(0<=n<=1000000)个数。
7
3
5
1
6
2
14
10
输出格式:
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.
区间和能被7整除的最长长度。
如果不存在,输出0。
5
说明/提示
In this example, 5+1+6+2+14 = 28.
二、题目分析
这是一道明显的前缀和
我们用sum[i]表示前缀和模7的值,若存在i≤j,满足sum[i]==sum[j],则区间 ( i,j ] 的和为7的倍数。
可能这里有人不太理解,举个例子:
8 % 7 =1,22 % 7 =1,22-8=14。
证:
设x%7==n, y%7==n (n<7)。
则(x-n)%7==0, (y-n)%7==0。
所以y-x=(y-n) - (x-n)。
所以(y-x)%7==0。
因此 O(N)扫出sum[0]~sum[6]第一次出现的位置l和最后一次出现的次数r,答案即为Max(r[i]-l[i])。
三、代码
#include<bits/stdc++.h>
using namespace std;
int a[100005],s[100005];
int l[7],r[7];
int main(){
int n,maxx=0;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
s[i]=(s[i-1]+a[i])%7;
}
for(int i=n;i>=1;i--){
l[s[i]]=i;
}
for(int i=1;i<=n;i++){
r[s[i]]=i;
}
for(int i=0;i<=6;i++){
maxx=max(r[i]-l[i],maxx);
}
cout<<maxx<<endl;
return 0;
}
可以看和理解,但不要抄代码哦~
拜拜!