欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CodeForces - 888E(思维,折半)

程序员文章站 2024-03-20 18:02:46
...

题目
分两半二进制枚举。
枚举第一部分。
第二部分每次枚举完去第一部分查找。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
#define N 40
#define LL long long
LL a[N];
set<LL>s;
int main()
{
	int n, n1, n2;
	LL m;
	scanf("%d%lld", &n, &m);
	for (int i = 0; i < n; i++)
	{
		scanf("%lld", &a[i]);
		a[i] %= m;
	}
	sort(a, a + n);
	n1 = n / 2, n2 = n - n1;
	LL sum, ans = 0;
	for (int i = 0; i < (1 << n1); i++)
	{
		sum = 0;
		for (int j = 0; j < n1; j++)
		{
			if ((1 << j) & i)sum += a[j];
			sum %= m;
		}
		s.insert(sum);
	}
	set<LL>::iterator it;
	for (int i = 0; i < (1 << n2); i++)
	{
		sum = 0;
		for (int j = 0; j < n2; j++)
		{
			if ((1 << j) & i)sum += a[j + n1];
			sum %= m;
		}
		it = s.upper_bound(m - sum - 1); it--;
		ans = max(ans, sum + *it);
	}
	cout << ans << endl;
	return 0;
}


相关标签: # 刷题之旅