【洛谷P3131】 【USACO16JAN】子共七

P3131 [USACO16JAN]子共七Subsequences Summing to Sevens


题目描述

Farmer John's 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, 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个数,求一个最长的区间,使得区间和能被7整除

输入输出格式

输入格式:

The first line of input contains (). The next

lines each contain the integer IDs of the cows (all are in the range

).

输出格式:

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.

这个题我看了一些题解的代码,发现


自己的代码真是太棒了!


不要问我为什么都用了longlong,数组开的那么大,因为我下面会解释的


我第一次交了80分,然后十分自信地认为开小数组或者没用longlong,然后改了,然后就过了


写一写题解吧,首先是进制的转化,这里用的是很常规的取摸(不懂得童鞋可以自行百度进制转换方法,这种方法很类似于短除法)。


先记录一个前缀和。两个前缀和mod7同余,则这两个前缀和的差值一定被7整除。


这里采取记余数,b[i]表示余数为i的前缀的最小下标


好了看程序吧,正确性应该是显然的

不懂得私信评论或Q:568251782均可

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

const int MAXN = 50000 + 10;

long long sum[MAXN],n;
long long b[7];
long long ans;

int main()
{
	scanf("%d", &n);
	for(long long i = 1;i <= n;i++)
	{
		int num;
		scanf("%d", &num);
		sum[i] = sum[i-1] + num;
	}
	for(int i = 1;i <= n;i++)
	{
		long long a;
		a = sum[i] % 7;
		if(a == 0)
		{
			ans = i;
		}
		else if(b[a])
		{
			if(ans < i - b[a])
			{
				ans = i - b[a];
			}
		}
		else
		{
			b[a] = i;
		}
	}
	printf("%d", ans);
	return 0;
}


转载于:https://www.cnblogs.com/huibixiaoxing/p/6537739.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值