[USACO16JAN]七子共题解

一、题目描述

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

可以看和理解,但不要抄代码哦~

拜拜!

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值