Hdu5776 sum 抽屉原理+同余定理

来源:互联网 发布:ant design 知乎 编辑:程序博客网 时间:2024/05/22 16:41

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
23 31 2 35 76 6 6 6 6
Sample Output
YESNO
Source
BestCoder Round #85
Recommend
wange2014

用前缀和去处理就好了,用 a[ i ] 去记录前 i 项之和对 m 的模。那么只要有两项是相同的,就存在所要求的连续串。

将 a[ 0 ]设为0可避免连续串从第一项开始的情况。

此外,由抽屉原理可得,n >= m 时一定存在。


#include <iostream>#include <cstdio>#include <map>#include <set>#include <vector>#include <queue>#include <stack>#include <cmath>#include <algorithm>#include <cstring>#include <string>using namespace std;#define INF 0x3f3f3f3ftypedef long long LL;int main(){    int t;    int n,m;    int a[100005];    scanf("%d",&t);    while(t--){        scanf("%d%d",&n,&m);        int t;        a[0]=0;        for(int i=1;i<=n;i++){            scanf("%d",&t);            a[i]=(a[i-1]+t)%m;        }        if(n>=m){            printf("YES\n");        }else{            sort(a+1,a+n+1);            int flag=1;            for(int i=1;i<=n;i++){                if(a[i]==a[i-1]){                    flag=0;                    break;                }            }            if(!flag){                printf("YES\n");            }else{                printf("NO\n");            }        }    }    return 0;}


0 0
原创粉丝点击