250 消除
/*
http://oj.daimayuan.top/course/5/problem/250
桌面上有 n
个方块,蜗蜗想把它们都消除掉。每个方块有个权值,第 i
个方块的权值等于 ai
。每一次消除蜗蜗有两种选择:
选择一个还没有被消除的方块 i
,付出 ai
的代价把它消除;
选择两个还没有被消除的方块 i,j (i≠j)
,付出 ai
xor aj
的代价把它们消除;
请问蜗蜗最少需要花费多少代价,能把 n
个方块都消除掉?
输入格式
第一行一个整数 n
表示方块数目。
第二行 n
个整数 a1,a2,...,an
。
输出格式
一行一个整数表示答案。
样例输入
3
1 4 5
样例输出
2
数据范围
对于 100%
的数据,保证 2≤n≤20,1≤ai≤100000。
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;
const int N = 25;
int a[N];
int n;
int ans;
int dp[1 << N];
bool isIn(int st, int a) {
return st & (1 << a);
}
int main()
{
scanf("%d",&n);
for (int i = 0; i < n; i++) scanf("%d",&a[i]);
memset(dp, 0x3f, sizeof dp);
dp[(1 << n) - 1] = 0;
for(int st = (1 << n) - 1; st >= 0; st--) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (isIn(st, i) && isIn(st, j)) {
int newst = st ^ (1 << i);
newst ^= (1 << j);
dp[newst] = min(dp[newst], dp[st] + (a[i] ^ a[j]) );
}
}
if (isIn(st, i)) {
int newst = st ^ (1 << i);
dp[newst] = min(dp[newst], dp[st] + a[i]);
}
}
}
printf("%d\n",dp[0]);
return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
2021-11-07 Leetcode 230. 二叉搜索树中第K小的元素 中序遍历
2021-11-07 Leetcode 217. 存在重复元素 哈希 排序
2021-11-07 Leetcode 160. 相交链表 哈希 链表
2020-11-07 LeetCode 327. 区间和的个数
2019-11-07 漫长的 windows caffe编译过程 (OnlyCpu)
2014-11-07 获取电驴首页推荐信息和指定栏目信息