CodeForces - 577B Modulo Sum

探讨如何判断一组数中是否存在子集,其元素和为给定数m的倍数。采用set容器存储所有可能的子集和,通过算法优化解决超时问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

给出n个数,求是否存在一个非空子集,这个子集中的数的和能够被m整除

Input

第一行输入nm(1 <= n <= 1e6,2 <= m <= 1e3)
第二行输入n个数,保证每个数都大于等于0,小于等于1e9

Output

若存在答案输出YES,否则输出NO

Examples

Input

3 5
1 2 3

Output

YES

Input

1 6
5

Output

NO

Input

4 6
3 1 1 3

Output

YES

Input

6 6
5 5 5 5 5 5

Output

YES

问能不能在大小是n的数列中取出几个数,使得他们的和是m的倍数

 

如果n>m,那么无论n个数是多少,都可以,这是一个定理

所以我们要讨论的就是n<=m的时候

对于1 2 2 3这个数列 

我们能得到的和有1   2  3   4  5   6 

重复的就直接去掉

所以用set容器来保存前i个数能得到的和

如果不用set应该会超时。

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int INF = 0x3f3f3f3f;
const int N=1000010;
int i,j,k;
int m;
int res,ans,cnt,temp;
int a[1000005];
int sum[1005];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    if(n>m)
    {
        printf("YES\n");
        return 0;
    }
    set<int>s;
    set<int>::iterator it;
    s.insert(a[0]%m);
    for(i=1; i<n; i++)
    {
        int l=-1;
        it=s.begin();
        int si=*it;
        if(si==0)
        {
            printf("YES\n");
            return 0;
        }
        for(it=s.begin(); it!=s.end(); ++it)
        {
            l++;
            int si=*it;
            sum[l]=(si+a[i])%m;
        }
        for(j=0; j<=l; j++)
         s.insert(sum[j]);
         s.insert(a[i]);
    }
    it=s.begin();
    int si=*it;
    if(si==0)
    {
        printf("YES\n");
        return 0;
    }
    printf("NO\n");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值