2019 ICPC Asia-East Continent Final M. Value(状压/枚举)
Pang believes that one cannot make an omelet without breaking eggs.
For a subset 𝐴A of {1,2,…,𝑛}{1,2,…,n}, we calculate the score of 𝐴A as follows:
- Initialize the score as 00.
- For any 𝑖∈𝐴i∈A, add 𝑎𝑖ai to the score.
- For any pair of integers (𝑖,𝑗)(i,j) satisfying 𝑖≥2i≥2, 𝑗≥2j≥2, 𝑖∈𝐴i∈A and 𝑗∈𝐴j∈A, if there exists positive integer 𝑘>1k>1 such that 𝑖𝑘=𝑗ik=j, subtract 𝑏𝑗bj from the score.
Find the maximum possible score over the choice of 𝐴A.
Input
The first line contains a single integer 𝑛n (1≤𝑛≤100000)(1≤n≤100000).
The second line contains 𝑛n integers 𝑎1,𝑎2,…,𝑎𝑛a1,a2,…,an (1≤𝑎𝑖≤1000000000)(1≤ai≤1000000000).
The third line contains 𝑛n integers 𝑏1,𝑏2,…,𝑏𝑛b1,b2,…,bn (1≤𝑏𝑖≤1000000000)(1≤bi≤1000000000).
Output
Print a single integer 𝑥x — the maximum possible score.
Examples
input
Copy
4
1 1 1 2
1 1 1 1
output
Copy
4
input
Copy
4
1 1 1 1
1 1 1 2
output
Copy
3
大意就是从1~n里选一部分数构成一个集合,计算能选出的集合的最大分数。其中一个集合的分数score是对于其中的每个元素x,score += a[x],同时对于每个有序对<x, y>(x小于y),如果满足且k不为1,则score -= b[y]。
首先执行一下类似筛法的过程,按照,,,等等分组(注意每组的基底不能为别的数的次幂,如果被标记直接跳过),然后枚举每组的选法,取最大的score,然后把每个组的分数加起来即可
至于枚举的话,由于每组个数cnt最大也就是20左右,因此可以采用二进制枚举。设k为状态,则遍历k从1到(1 << cnt) - 1,这样对于每个k实际上就构成了一种选法(按位考虑,第i位表示选组里的第i个数),然后根据枚举到的k来选出相应的组里的数,两重循环遍历计算答案即可。注意要想更快判断次幂的话可以用结构体存数,x表示数,num表示是基底的几次幂,如果a.num % b.num == 0则表示a.x是b.x的次幂。
注意因为分组的时候忽略了1,而1必选,因此最后要加上a[1]。
#include <iostream>
#include <vector>
#define int long long
using namespace std;
int n, a[100005], b[100005];
bool vis[100005] = { 0 };
struct point
{
int x;
int num;//次幂数
};
long long ans = 0, tmp_ans = 0;
signed main()
{
freopen("data.txt", "r", stdin);
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++) cin >> b[i];
for(int i = 2; i <= n; i++)
{
if(vis[i]) continue;
vector<point> tmp;
int cnt = 0;
for(int j = i; j <= n; j *= i)
{
tmp.push_back({j, ++cnt});
vis[j] = 1;
}
long long max_tmp_ans = -1e17;
for(int k = 0; k < (1 << cnt); k++)//二进制下的k就是状态 第一个肯定得选
{
vector<point> choose;
for(int w = 0; w < cnt; w++)
{
if(k & (1 << w)) choose.push_back(tmp[w]);
}
tmp_ans = 0;
for(int j = 0; j < choose.size(); j++)
{
tmp_ans += a[choose[j].x];
for(int k = j + 1; k < choose.size(); k++)
{
if(choose[k].num % choose[j].num == 0)
{
tmp_ans -= b[choose[k].x];
}
}
}
max_tmp_ans = max(max_tmp_ans, tmp_ans);
}
ans += max_tmp_ans;
}
cout << ans + a[1];
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!