【HDU4016】Magic Bitwise And Operation

参考:https://blog.csdn.net/qq_39826163/article/details/83240289
参考:https://blog.csdn.net/kongming_acm/article/details/6771824
题目:http://acm.hdu.edu.cn/showproblem.php?pid=4016

题目理解

  • 题目意思是从n个数中选k个数,进行与运算,找到最小值。
  • 使用暴力法肯定会超时
  • 但如果给数据进行预排序,设置剪枝条件,就会好很多
  • a数组 用来保存输入的数据,并进行升序排序。
  • b数组 b[i]用来存储 a[i] 与 a[i]后面所有数据 进行相与的结果

解题思路

  • 可以利用两个数相与只会变小或者不变来剪枝
  • void DFS(int pos, int num, Long x);
    • pos(数据位置)
    • num(已经选取个数)
    • x(当前已选取数据的相与值)
  • DFS流程:
    • 是先递归到找到k个值,更新res,然后回退到选取了k-1一个数据的时候,
    • 不选此时的第k个数据,而是选取下一个数据,检测此时的数据是否小于res,如果是则更新。
    • 在往后选取数据的时候如果((b[pos] & x) >= res)则直接return。
#include<bits/stdc++.h>
using namespace std;

#define Long long long int

const Long INF = ((Long)1 << 61) - 1;

class Sloution
{
public:
	Sloution(int _n, int _k)
		:n(_n), k(_k), res(INF)
	{
		a.resize(n);
		b.resize(n, INF);
	}
	Long GetRes() { return res; }
	void GetNode();
	void DFS(int pos, int num, Long x);
private:
	int n;
	int k;
	Long res;
	vector<Long> a;
	vector<Long> b;
};

void Sloution::GetNode()
{
	Long input = 0;
	for (int i = 0; i < n; ++i)
	{
		cin >> input;
		a[i] = input;
	}
	sort(a.begin(), a.end());
	b[n - 1] = a[n - 1];
	for (int i = n-2; i >= 0; --i)
	{
		b[i] = b[i + 1] & a[i];
	}
}

void Sloution::DFS(int pos, int num, Long x)
{
	if (k == num){ res = min(res, x); return; }
	Long tmp = x;
	if (pos == n) return;
	if ((b[pos] & tmp) >= res) return;
	DFS(pos + 1, num + 1, x & a[pos]);
	DFS(pos + 1, num, x);
}

int main()
{
	int T = 0;//1<=T<=10
	int n = 0;//1<=n<=40 1<=a[i]<=2^60
	int k = 0;
	cin >> T;
	while (T--)
	{
		cin >> n;
		cin >> k;
		Sloution s(n, k);
		s.GetNode();
		s.DFS(0, 0, INF);
		cout << s.GetRes() << endl;
	}

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值