天生我材必有用,千金散尽还复来。 仰天大笑出门去,我辈岂是蓬蒿人。 大鹏一日同风起,扶摇直上九万里。 十步杀一人,千里不留行。 事了拂衣去,深藏身与名。 安能摧眉折腰事权贵,使我不得开心颜! 且乐生前一杯酒,何须身后千载名? 愿将腰下剑,直为斩楼兰。
 

前缀和

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

 

posted @ 2018-03-27 13:31  gudy  阅读(173)  评论(0编辑  收藏  举报