超大背包问题

这篇博客探讨了如何使用C++的next_permutation和prev_permutation生成全排列,并介绍了超大背包问题。在超大背包问题中,面对大量物品和权重,由于n较小,不适合使用动态规划,而是采用将物品拆分成两半再枚举的方法。通过优化,利用二分搜索在O(n * 2^(n / 2))的时间复杂度内找到最优解。
摘要由CSDN通过智能技术生成

得意问题开始之前, 首先介绍一下利用C++ 头文件<algorithm>中的next_permutation()和pre_permutation产生0, 1, 2, 3, ... N - 1全排列。 这两个函数

产生全排的办法是通过字典序的原理。 next_permutation() 按照递增的办法产生字典序的下一个(唯一确定的, 与当前的排列之间不能夹杂了任何可行的

排列)。 prev_permutation() 产生当前排列的字典序的上一个排列, 是按照递减的顺序。 即产生的字典序比当前排列小的。

下面利用next_permutation产生0, 1, ... N - 1 的所有的全排列的方法:

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3); // 必须有这一步, 否则可能产生不完全

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}
运行结果如下:

当然也可以采用递归的办法产生, 方法如下:

#include <iostream>

using namespace std;
void swap(char *fir, char *sec)
{
    char temp = *fir;
    *fir = *sec;
    *sec = temp;
}

/* arr is the string, curr is the current index to start permutation from and size is sizeof the arr */
void permutation(char * 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值