参考: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;
}