01背包分支限界算法C++
时间: 2023-12-17 13:28:41 浏览: 149
以下是01背包分支限界算法的C++代码实现:
```c++
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1010;
struct Node
{
int v, w;
double u; // u表示单位价值
bool operator< (const Node &t) const
{
return u < t.u;
}
}node[N];
int n, m;
double ans;
priority_queue<double> q;
void dfs(int u, int v, double w)
{
if (v > m) return;
if (u == n)
{
ans = max(ans, w);
return;
}
if (w + q.top() * (m - v + 1) <= ans) return; // 剪枝
q.push(node[u + 1].u);
dfs(u + 1, v + node[u + 1].v, w + node[u + 1].w);
q.pop();
dfs(u + 1, v, w);
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> node[i].v >> node[i].w;
node[i].u = (double)node[i].w / node[i].v;
}
sort(node + 1, node + n + 1);
dfs(0, 0, 0);
printf("%.2lf\n", ans);
return 0;
}
```
阅读全文