[HDU] [5776] Sum

Problem Description

Loading...

Problem Analysis

Chinese statement:
Given a sequence, determine whether there exists a contiguous subarray whose sum is a multiple of m. Output YES if it exists, otherwise output NO.

Official solution:
Precompute the prefix sums. As soon as two prefix sums are congruent modulo m, the segment between them forms a contiguous subarray whose sum is a multiple of m. In addition, by the pigeonhole principle, once n is greater than or equal to m, the answer is always YES. Complexity O(n).

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include<stdio.h>
#include<string.h>
int flag[10000];
int main() {
    int T;
    scanf("%d",&T);
    while(T--) {
        int n,m;
        scanf("%d %d",&n,&m);
        memset(flag,0,sizeof(flag));
        flag[0]=1;
        bool win=false;
        int sum=0;
        for(int i=0; i<n; i++) {
            int t;
            scanf("%d",&t);
            sum=(sum+t)%m;
            if(flag[sum]==1)
                win=true;
            flag[sum]=1;
        }
        if(win)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...