zoukankan      html  css  js  c++  java
  • 前缀和

    hdu5776 sum

    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 (1n1000001m5000).
    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

     初试前缀和,对于求区间和很好用

    关键代码:

    //得到前缀和
            for(int i = 1;i <= n;i++){
                cin >> a[i];
                sum[i] = sum[i - 1] + a[i];
            }

    这个题要求是否有个连续区间的和可以整除m

    想到区间和,但又不能暴力求所有的区间和

    对每个前缀和都对m求模,如果出现0,肯定可以;如果出现两个相同的数,也是可以(加上两个数中间的和正好一个轮回,说明中间的和可以整除m)。

    #include<iostream>
    using namespace std;
    const int MAXN = 100000;
    int sum[MAXN + 2] = {0};
    int a[MAXN + 2];
    int main()
    {
        int T,n,m;
        cin >> T;
        while(T--){
            int s[5002] = {0};
            int flag = 0;
            cin >> n >> m;
            //得到前缀和
            for(int i = 1;i <= n;i++){
                cin >> a[i];
                sum[i] = sum[i - 1] + a[i];
            }
            //处理前缀和
            for(int i = 1 ; i <= n;i++){
                sum[i] %= m;
                s[sum[i]] += 1;
    
                //cout << sum[i] <<endl;
    
                if(sum[i] == 0){
                    flag = 1;
                    break;
                }
            }
            for(int i = 0; i < 5002;i++){
                if(s[i] > 1){
                    flag = 1;
                    break;
                }
            }
            if(flag)
                cout << "YES" << endl;
            else
                cout << "NO" << endl;
    
        }
    
      //  for(int i = 1 ; i <= N;i++){
        //    cout << sum[i] << endl;
       // }
    /*    int l,r;
        int T;
        cin >> T;
        while(T--){
            cin >> l >> r;
            cout << sum[r] - sum[l - 1] << endl;
        }
    
        */
        return 0;
    }
  • 相关阅读:
    SVN trunk(主线) branch(分支) tag(标记) 用法详解和详细操作步骤
    SVN版本控制—branches、trunk、tag篇
    SVN将项目代码加入svn版本控制
    交换机详细解读
    ESXI
    vSphere
    VM虚拟机?
    Linux 01 LiunxvI命令大全
    “高可用性”(High Availability)??
    说一说,正常上线的流程
  • 原文地址:https://www.cnblogs.com/gudygudy/p/8656965.html
Copyright © 2011-2022 走看看