背包问题

本文介绍了一个使用C++实现的动态规划算法,解决物品选择问题,包括读取物品数量、价值和重量,然后计算在限定总重量下能获取的最大价值。
#include<iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
#define MAXSIZE 1000
int A[MAXSIZE+1][MAXSIZE+1],B[MAXSIZE+1][MAXSIZE+1];
int c[MAXSIZE+1],w[MAXSIZE+1];
int F(int n,int v)
{
    if(n==0) return 0;
    if( !A[n][v] && v >= c[n])
        A[n][v] = F(n-1,v-c[n]) +w[n];
    if(!B[n][v])
        B[n][v] = F(n-1,v);
    return A[n][v]>B[n][v]?A[n][v]:B[n][v];
}
int main()
{    int n,v;

ofstream examplefile ("example");
      if (examplefile.is_open()) {
          examplefile << "This is a line.\n";
          examplefile << "This is another line.\n";
          examplefile.close();
      }

    ifstream in("1" ,ios_base::binary);
    ofstream out("2.txt");
    in>>n>>v;
    for(int i=1;i<=n;i++)
  in>>c[i]>>w[i];
    out<<F(n,v);
    out.flush();
    out.close();
    cin>>n;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值