当前位置: 首页 > ds >正文

【分组背包 数论】P12160 [蓝桥杯 2025 省 Java B] 2 的幂|普及+

本文涉及知识点

C++背包问题
数论:质数、最大公约数、菲蜀定理

P12160 [蓝桥杯 2025 省 Java B] 2 的幂

题目描述

小明很喜欢 2 2 2 的幂,所以他想对一个长度为 n n n 的正整数数组 { a 1 , a 2 , … , a n } \{a_1, a_2, \dots, a_n\} {a1,a2,,an} 进行改造。他可以进行如下操作任意多次(可以是 0 0 0 次):任选一个数 a i a_i ai 加上任意正整数,但不能使得加完之后的结果超过 10 5 10^5 105

在操作任意次后,小明希望所有数的乘积是 2 k 2^k 2k 的倍数。他想知道总共需要加的数的总和至少是多少?

输入格式

输入共两行。

  • 第一行为两个正整数 n , k n, k n,k
  • 第二行为 n n n 个由空格分开的正整数 a 1 , a 2 , … , a n a_1, a_2, \dots, a_n a1,a2,,an

输出格式

输出共 1 1 1 行,一个整数表示答案。如果不能满足条件,输出 − 1 -1 1

输入输出样例 #1

输入 #1

3 9
19 10 3

输出 #1

12

说明/提示

样例说明

将三个数分别加到 24 , 16 , 4 24, 16, 4 24,16,4,它们的乘积为 1536 = 2 9 × 3 1536 = 2^9 \times 3 1536=29×3,加的数的总和为 5 + 6 + 1 = 12 5 + 6 + 1 = 12 5+6+1=12

评测用例规模与约定

  • 对于 20 % 20\% 20% 的评测用例, n , k ≤ 10 n, k \leq 10 n,k10
  • 对于 100 % 100\% 100% 的评测用例, 1 ≤ n ≤ 500 1\leq n \leq 500 1n500 1 ≤ k ≤ 5000 1\leq k \leq 5000 1k5000 1 ≤ a i ≤ 100000 1\leq a_i \leq 100000 1ai100000

贪心(错误)

任意x都是可以表示为
{ y,b,c }
其中 x = 2 b × c x= 2^b\times c x=2b×c,初始b是0, c是x。如果c是偶数,y等于0;否则y = 2^b。
这些元素出堆、入队K次。出堆后:c += y ,ans+=y。c/=2 b++,重新计算y。入堆。如果入堆前发现 2 b × c > 1 e 5 2^b\times c > 1e5 2b×c>1e5,返回-1。
结果就是ans。
贪心会陷入局部最优解。比如:K=4,a={1,12},直接将12改成16就可以了。没有必要修改1,让人想到反悔贪心,而反悔贪心,让我想到分组背包。

分组背包

f(x,b)将x变成 2 b 2^b 2b的倍数,需要增加的数。如果x是 2 b 2^b 2b的倍数,f(x,b)是0,否则f(x,b)=g(x,b)= x 2 b × 2 b + 2 b \frac{x}{2^b}\times {2^b}+{2^b} 2bx×2b+2b
如果g(x,b) > 1e5,则f(x,b) = LLONG_MAX/2。
dp[i][k] 修改了前i个数,前i个数的乘积是 2 k 2^k 2k倍最少需要增加多少。
注意:如果最终结果dp.back()[k],如果 >= LLONG_MAX/2,返回-1。
三层循环,前两层循环枚举前驱状态i,k,第三层循环当前选择b=0 to 20。
动态规划的初始值:dp[0][0]=0,其它LLONG_MAX/2。
时间复杂度:O(NKlog1e5)

代码

核心代码

#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>
#include<array>#include <bitset>
using namespace std;template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {in >> pr.first >> pr.second;return in;
}template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t);return in;
}template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);return in;
}template<class T1, class T2, class T3, class T4, class T5, class T6, class T7 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4,T5,T6,T7>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t) >> get<4>(t) >> get<5>(t) >> get<6>(t);return in;
}template<class T = int>
vector<T> Read() {int n;cin >> n;vector<T> ret(n);for (int i = 0; i < n; i++) {cin >> ret[i];}return ret;
}
template<class T = int>
vector<T> ReadNotNum() {vector<T> ret;T tmp;while (cin >> tmp) {ret.emplace_back(tmp);if ('\n' == cin.get()) { break; }}return ret;
}template<class T = int>
vector<T> Read(int n) {vector<T> ret(n);for (int i = 0; i < n; i++) {cin >> ret[i];}return ret;
}template<int N = 1'000'000>
class COutBuff
{
public:COutBuff() {m_p = puffer;}template<class T>void write(T x) {int num[28], sp = 0;if (x < 0)*m_p++ = '-', x = -x;if (!x)*m_p++ = 48;while (x)num[++sp] = x % 10, x /= 10;while (sp)*m_p++ = num[sp--] + 48;AuotToFile();}void writestr(const char* sz) {strcpy(m_p, sz);m_p += strlen(sz);AuotToFile();}inline void write(char ch){*m_p++ = ch;AuotToFile();}inline void ToFile() {fwrite(puffer, 1, m_p - puffer, stdout);m_p = puffer;}~COutBuff() {ToFile();}
private:inline void AuotToFile() {if (m_p - puffer > N - 100) {ToFile();}}char  puffer[N], * m_p;
};template<int N = 1'000'000>
class CInBuff
{
public:inline CInBuff() {}inline CInBuff<N>& operator>>(char& ch) {FileToBuf();while (('\r' == *S) || ('\n' == *S) || (' ' == *S)) { S++; }//忽略空格和回车ch = *S++;return *this;}inline CInBuff<N>& operator>>(int& val) {FileToBuf();int x(0), f(0);while (!isdigit(*S))f |= (*S++ == '-');while (isdigit(*S))x = (x << 1) + (x << 3) + (*S++ ^ 48);val = f ? -x : x; S++;//忽略空格换行		return *this;}inline CInBuff& operator>>(long long& val) {FileToBuf();long long x(0); int f(0);while (!isdigit(*S))f |= (*S++ == '-');while (isdigit(*S))x = (x << 1) + (x << 3) + (*S++ ^ 48);val = f ? -x : x; S++;//忽略空格换行return *this;}template<class T1, class T2>inline CInBuff& operator>>(pair<T1, T2>& val) {*this >> val.first >> val.second;return *this;}template<class T1, class T2, class T3>inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {*this >> get<0>(val) >> get<1>(val) >> get<2>(val);return *this;}template<class T1, class T2, class T3, class T4>inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);return *this;}template<class T = int>inline CInBuff& operator>>(vector<T>& val) {int n;*this >> n;val.resize(n);for (int i = 0; i < n; i++) {*this >> val[i];}return *this;}template<class T = int>vector<T> Read(int n) {vector<T> ret(n);for (int i = 0; i < n; i++) {*this >> ret[i];}return ret;}template<class T = int>vector<T> Read() {vector<T> ret;*this >> ret;return ret;}
private:inline void FileToBuf() {const int canRead = m_iWritePos - (S - buffer);if (canRead >= 100) { return; }if (m_bFinish) { return; }for (int i = 0; i < canRead; i++){buffer[i] = S[i];//memcpy出错			}m_iWritePos = canRead;buffer[m_iWritePos] = 0;S = buffer;int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);if (readCnt <= 0) { m_bFinish = true; return; }m_iWritePos += readCnt;buffer[m_iWritePos] = 0;S = buffer;}int m_iWritePos = 0; bool m_bFinish = false;char buffer[N + 10], * S = buffer;
};class Solution {public:long long Ans( const int K, vector<int>& a) {	auto Need = [&](int x, int bit) {const int mask = 1 << bit;if (0 == x % mask) { return 0; }const int iNew = x + mask - x % mask;if (iNew > 100'000) { return -1; }return iNew-x;};vector<long long> pre(K + 1,LLONG_MAX/2);pre[0] = 0;for (const auto& x : a) {vector<long long> cur(K + 1, LLONG_MAX / 2);for (int ip = 0; ip <= K; ip++) {for (int b = 0; (b < 20)&&(ip+b<=K); b++) {const int iAdd = Need(x, b);if (-1 == iAdd) { continue; }cur[ip + b] = min(cur[ip + b], pre[ip] + iAdd);}}pre.swap(cur);}const auto& ans = pre.back();return (ans >= LLONG_MAX / 2) ? -1 : ans;}};int main() {
#ifdef _DEBUGfreopen("a.in", "r", stdin);
#endif // DEBUG	ios::sync_with_stdio(0); cin.tie(nullptr);//CInBuff<> in; COutBuff<10'000'000> ob;int N,K;cin >> N >> K  ;auto a = Read<int>(N);
#ifdef _DEBUG	printf("K=%d", K);//Out(W, ",W=");//Out(edge, ",edge=");Out(grid, ",grid=");Out(a, ",a=");Out(rr, ",rr=");//  //Out(ab, ",ab=");//  //Out(par, "par=");//  //Out(que, "que=");//  //Out(B, "B=");
#endif // DEBUG	auto res = Solution().Ans(K, a);	cout << res << "\n";return 0;
};

单元测试

		int  K;vector<int> a;TEST_METHOD(TestMethod11){K = 9, a = { 19,10,3 };auto res = Solution().Ans(K,a);AssertEx(12LL, res);}TEST_METHOD(TestMethod12){const int X = 5 * 5 * 5 * 5 * 5;K = 5, a = { X };auto res = Solution().Ans(K, a);AssertEx(X/32*32LL+32-X, res);}TEST_METHOD(TestMethod13){K = 20, a = {1 };auto res = Solution().Ans(K, a);AssertEx(-1LL, res);}TEST_METHOD(TestMethod14){K = 12, a = { 100000,64 };auto res = Solution().Ans(K, a);AssertEx(64LL, res);}TEST_METHOD(TestMethod15){K = 4, a = { 33,13 };auto res = Solution().Ans(K, a);AssertEx(3LL, res);}

扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771
如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17
或者 操作系统:win10 开发环境: VS2022 C++17
如无特殊说明,本算法用**C++**实现。

http://www.xdnf.cn/news/8618.html

相关文章:

  • MySQL 第五讲---基础篇 表的约束
  • 每个元素后面加“、”,但最后一个元素不加
  • 点云处理的瑞士军刀PCL几何库
  • 基于Java(GUI)实现五子棋
  • 【AI】小参数,大影响:从OpenAI参数看AI开发挑战
  • Python打卡训练营学习记录Day34
  • 文章记单词 | 第104篇(六级)
  • MySQL --- 事务
  • 【Linux系列】EVS 与 VBD 的对比
  • 文章记单词 | 第103篇(六级)
  • 永磁同步电机参数辨识算法--拓展卡尔曼滤波参数辨识
  • 探索微观世界的“度量衡”:显微测量仪器解析
  • 《C++20新特性全解析:模块、协程与概念(Concepts)》
  • Python包管理器:uv
  • 目前,Navicat 17.1 版本的用户管理功能无法使用,如何回退到上一个版本?关于之前提到的转置功能?
  • Three.js 中的 Octree(八叉树)详解
  • android studio第一次编译apk,用时6分钟
  • 安装openEuler操作系统
  • 49页 @《人工智能生命体 新启点》中國龍 原创连载
  • ResNet、MobileNet、YOLOv3、DeepLabv3+ 比较
  • 数据库表设计题目
  • OpenCV CUDA 模块图像过滤------创建一个线性滤波器(Linear Filter)函数createLinearFilter()
  • 【Golang笔记03】error、panic、fatal错误处理学习笔记
  • Mysql逻辑架构
  • leetcode-hot-100 (普通数组)
  • 数据结构(6)线性表-队列
  • 计算机系统结构 -第三章:指令集并行 -1
  • Z世代消费新图鉴:从盲盒经济到可持续浪潮,解码年轻世代的消费密码
  • 方洪波摸着雷军,“甩掉”小米
  • Linux里more 和 less的区别