P3131 [USACO16JAN]子共七Subsequences Summing to Sevens(一維字首和)
題目描述
Farmer John's NN 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 61…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 NN (1 \leq N \leq 50,0001≤N≤50,000). The next NN
lines each contain the NN integer IDs of the cows (all are in the range
0 \ldots 1,000,0000…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: 複製
7 3 5 1 6 2 14 10
輸出樣例#1: 複製
5
說明
In this example, 5+1+6+2+14 = 28.
如果用兩個for迴圈分別對 (sum[j]-sum[i])%7,
n^2複雜度
我們可以先直接求%7意義下的字首和,然後只要看看餘數的重複就可以了。
這裡需要用到一個定理:若兩個數相減%7==0,那麼這兩個數%7的餘數一定相同 我們只要求出相同的一個餘數第一次和最後一次之間的長度即是最長長度 但是我們不知道哪個餘數最長,
所以: 列舉0~6 共7個餘數各自的最長長度,再在他們7個裡找最長的
#include <iostream>
#include<cmath>
using namespace std;
int a[50005],f[7],l[7];;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
a[i]=(a[i]+a[i-1])%7;
}
for(int i=1;i<=n;i++)
{
l[a[i]]=i;
}
for(int i=n;i>=1;i--)
{
f[a[i]]=i;
}
int maxnum=0;
for(int i=0;i<=6;i++)
{
maxnum=max(maxnum,l[i]-f[i]);
}
cout<<maxnum;
return 0;
}