HDU5776 sum【前缀和+模除+水题】

本文探讨了一道经典的算法题目,即判断一个整数序列是否存在连续子序列使其和能被特定整数m整除。通过分析前缀和的性质,提出了一种高效算法,并给出了完整的C++实现代码。

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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值