算法竞赛进阶指南,111 页,双向搜索,先搜一半,再搜一半
本题要点:
1、数据直接用 long long 来存,避免溢出麻烦
2、从大到小排序,先处理前一半的数据, 看看可以组合出来哪些 数的和是 小于等于 w的( 和 <= w)。
用 vector 存储这些和,去重,排序。这里使用vector的 unique 函数 和erase 函数。
3、 处理后面一半,得到若干数的和 为sum(sum <= w)。
然后在 vector 中二分查找, 最大的一个数 k 使得, k + sum <= w;
这里使用了 stl的 算法 upper_bound
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MaxN = 50;
long long w, ans, g[MaxN], n, m;
vector<long long> v;
bool cmp(long long a, long long b)
{
return a > b