Subsequences Summing to Sevens(前缀和)

本文介绍了一种算法问题,即寻找整数序列中满足特定条件(元素之和为7的倍数)的最大连续子序列,并提供了完整的代码实现及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Subsequences Summing to Sevens

时间限制: 1 Sec   内存限制: 64 MB
提交: 55   解决: 29
[ 提交][ 状态][ 讨论版]

题目描述

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…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. 

输入

The first line of input contains N (1≤N≤50,000). The next N lines each contain the N integer IDs of the cows (all are in the range 0…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.

You may want to note that the sum of the IDs of a large group of cows might be too large to fit into a standard 32-bit integer. If you are summing up large groups of IDs, you may therefore want to use a larger integer data type, like a 64-bit "long long" in C/C++. 

样例输入

7
3
5
1
6
2
14
10

样例输出

5

提示

In this example, 5+1+6+2+14 = 28.

又是一道前缀和的问题,没有修改插入,只是静态的查询,用前缀和进行预处理简直给力。

通过预处理前缀和mod7,放到sum数组中,如果两个位置的sum相等,即他们取余7之后的结果相同,则他们的差,也就是后面减去前面,剩下的部分,取余7等于0。

遍历取最长的就好了。

#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define pi acos(-1.0)
#define maxn (101000 + 50)
#define mol 1000000009
#define inf 0x3f3f3f3f
#define Lowbit(x) (x & (-x))
using namespace std;
typedef long long int LLI;

int a[maxn],sum[maxn];
int vis[10],n,re;

int main() {
   memset(vis,-1,sizeof(vis));
   int n;
   while(scanf("%d",&n)!=EOF){
        int tmp;
        for(int i=1;i<=n;i++){
            scanf("%d",&tmp);
            sum[i] = (sum[i-1] + tmp)% 7;
        }
        int re = 0;
        for(int i=1;i<=n;i++){
            if(vis[sum[i]] == -1){
                vis[sum[i]] = i;
            }
            else re = max(re , i - vis[sum[i]]);
        }
        printf("%d\n",re);
   }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值