• 【洛谷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;
    }
    


  • 相关阅读:
    Python--初识函数
    Python中的文件操作
    Python中的集合
    Python中的编码和解码
    Python的关键字is和==
    Python中的字典
    Python中的列表和元组
    Python中几种数据的常用内置方法
    Python的编码
    python_while
  • 原文地址:https://www.cnblogs.com/huibixiaoxing/p/6537739.html
Copyright © 2020-2023  润新知