CF577B Modulo Sum(鹊巢原理,背包)

在这里插入图片描述
思路:子序列和是经典的背包问题,但对于这题来说,因为和太大了,需要进一步思考.考虑 m m m很小,应当从这点入手,我们只考虑是否有子序列之和 % m 为 0 \%m为0 %m0
那么我们考虑对所有的子序列和模 m m m
此时需要一点灵感,因为即使这样,背包空间是m,物品数量是n,这么做仍然是会超时的.此时,标签中的鹊巢原理就出现作用了,思考,当n>m,时,有大于m件的物品放入m个抽屉中,一定会出现两个值相同的情况,只需取n<m的情况就可以了.

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3+5;
const int INF = 1e9+7;
typedef long long ll;
typedef pair<int,int> pii;
#define all(a) (a).begin(), (a).end()
#define pb(a) push_back(a)
vector<int> G[maxn];
//前向星
// for(int i=head[u];i!=-1;i=nxt[i]) v = to[i]
//int nxt[maxn],head[maxn],to[maxn];// head[u],cnt 初始值是-1
//int tot = -1;
//void add(int u,int v){
//	nxt[++tot] = head[u];
//	head[u] = tot;
//	to[tot] = v;
//}
bool dp[maxn][maxn];int a[maxn];
int main(){
    ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n,m;cin>>n>>m;
	if(n>m){
		cout<<"YES\n";
		exit(0);
	}
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=n;i++) a[i]%=m;
		bool ok = false;
		for(int i=1;i<=n;i++){
			dp[i][a[i]] = 1;
			for(int j=1;j<=m;j++){
				dp[i][j]|=dp[i-1][j];
				dp[i][(j+a[i])%m]|=dp[i-1][j];
 			}
 			ok|=dp[i][0];
		}
		if(ok) cout<<"YES\n";
		else cout<<"NO\n";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

minato_yukina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值