6Luffy6

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

P3131 [USACO16JAN] Subsequences Summing to Sevens S

传送锚点:

[USACO16JAN]Subsequences Summing to Sevens S - 洛谷

题目描述

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 16, 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 (1N50,000). The next N

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

01,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

样例输入 #1

7
3
5
1
6
2
14
10

样例输出 #1

5

提示

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

思路

这题结合前缀和和数学知识,我一开始的想法是算出前缀和存储到一个数组,使用二重循环求出最大能被余7的连续个数,但样例点有5万个,会超时

首先我们要对前缀和加上第i个数字都进行模7处理,然后用到一个小定理,若两个数相减 (mod 7=0) ,那么这两个数 mod 7 的余数一定相同!

然后我们回想一下我们是怎么求一维数组下的一段前缀和,是不是用sum[r] - sum[l - 1](sum为存储前缀和),所以我们引入l、r两个数组,数组大小都为7,

l[i]存%7为i的最小值l- 1,r[i]存%7为i的最大值r,-1代表没有%7为i的前缀和,注意l数组中第一个值初始化为0,因为当任意前缀和sum[x]%7等于0时,最长区间就是x

code

#include <iostream>

using namespace std;
int main() {
    int n;
    cin >> n;
    int l[7], r[7];//余数
    fill(l, l + 7, -1);
    fill(r, r + 7, 0);
    l[0] = 0;
    int sum = 0;//前缀和
    for (int i = 1; i <= n; ++i) {
        int a;
        cin >> a;
        sum = (sum + a) % 7;
        if (l[sum] == -1) l[sum] = i;
        r[sum] = i;
    }
    int ans = 0;
    for (int i = 0; i < 7; ++i) {
        if (l[i] != -1) {
            ans = max(r[i] - l[i], ans);
        }
    }
    cout << ans;
    return 0;
}

posted on   极客三刀流  阅读(29)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示