zoukankan      html  css  js  c++  java
  • HDU5776 sum【前缀和+模除】

    sum

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
    Total Submission(s): 2530    Accepted Submission(s): 966


    Problem Description

    Given a sequence, you're asked whether there exists a consecutive subsequence whose sum is divisible by m. output YES, otherwise output NO
     
    Input
    The first line of the input has an integer T (1T10), which represents the number of test cases. 
    For each test case, there are two lines:
    1.The first line contains two positive integers n, m (1n100000, 1m5000).
    2.The second line contains n positive integers x (1x100) according to the sequence.

    Output
    Output T lines, each line print a YES or NO.

    Sample Input
    2 3 3 1 2 3 5 7 6 6 6 6 6
     
    Sample Output
    YES NO
     
    Source

    问题链接HDU5776 sum

    题意简述:(略)

    问题分析

    这是一个连续子段和能否被整除的问题

    连续子段和可以由前缀和的差得到,所有将问题转换为求前缀和的问题。

    即使得到前缀和,求两个前缀和的差(子段和)其计算复杂度为O(n*n),也是比较难以接受的。

    对所有前缀和模除m,得到其余数放在数组中,如果有两个以上相同的余数,说明子段和能够被m整除。

    由于最大的m比较小(1<=m<=5000),所有时间复杂度上看还是比较快的。

    原始数据和前缀和是没有必要存储的,只需要存储前缀和的余数的计数就够用了,可以省去许多存储。

    一种特殊的情况是,如果有前缀和除以m余数为0的话,说明存在连续的子段能够被m整除。这种情形,程序中需要做特殊的处理。

    程序说明:(略)


    AC的C++语言程序如下:

    /* HDU5776 sum */
    
    #include <iostream>
    #include <string.h>
    
    using namespace std;
    
    const int M = 5000;
    int prefixsum, remainder[M];
    
    
    int main()
    {
        int t, n, m, a;
    
        cin >> t;
        while(t--) {
            cin >> n >> m;
    
            memset(remainder, 0, sizeof(remainder));
            prefixsum = 0;
            remainder[0] = 1;
            for(int i=1; i<=n; i++) {
                cin >> a;
    
                prefixsum += a;
                prefixsum %= m;
                remainder[prefixsum]++;
            }
    
            bool flag = false;
            for(int i=0; i<m; i++)
                if(remainder[i] >= 2) {
                    flag = true;
                    break;
                }
    
            cout << (flag ? "YES" : "NO") << endl;
        }
    
        return 0;
    }





  • 相关阅读:
    slf4j + log4j 记录日志
    Executors介绍
    Java集合(JDK1.6.0_45)
    Java多线程系列目录(共43篇)
    线程池体系
    FutureTask
    23种设计模式分类
    结构型 之 适配器模式
    信号量Semaphore详解以及应用
    Excel格式转化工具
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7563701.html
Copyright © 2011-2022 走看看