日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++实现动态规划算法之解决0-1背包问题

發布時間:2023/12/20 c/c++ 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++实现动态规划算法之解决0-1背包问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

c++實現動態規劃算法解決0-1背包問題

Main.cpp

//============================================================================ // Name : Knapsack.cpp // Author : // Version : 1.0 // Copyright : Your copyright notice // Description : 0-1背包算法問題 //============================================================================#include <iostream> #include<cstdlib> #include"Knapsack.h" #include<fstream> #include <string> using namespace std;const char up='|'; const char left='-'; const char least='\\'; int** result; //結果列表int *weight; //物品重量數組 int *value; //價值數組void fileInit(int &n,int &max)// {ifstream in("input.txt"); //read fileif(!in){cout<<"file is not exist!";return;}int num;int maxWeight;in>>num;in>>maxWeight;cout<<endl<<"物品數量:"<<num<<endl<<"最大重量:"<<maxWeight<<endl;weight=new int[num];value=new int[num];cout<<"重量數組:\t";for(int i=0;i<num;i++){in>>weight[i];cout<<setw(5)<<weight[i];}cout<<endl;cout<<"價值數組:\t";for(int i=0;i<num;i++){in>>value[i];cout<<setw(5)<<value[i];}cout<<endl;n=num;max=maxWeight;in.close(); } int main() {cout << "0-1背包問題演示" << endl<<"從文件input.txt中初始化數據"; // prints Titleint number=0; //物品數量int maxWeight=0; //背包最大重量fileInit(number,maxWeight);if(number==0){return 0;}result=new int *[number+1];for(int i = 0;i <= number;i++){result[i]=new int[maxWeight+1];}//int* location; //最優解集合inItResult(result,number+1,maxWeight+1); //init the resultcout<<"the init table is:"<<endl;print(result,number+1,maxWeight+1);cout<<"the result table is:"<<endl;myKnapsack(value,weight,maxWeight,number,result);print(result,number+1,maxWeight+1); //打印結果表格cout<<endl<<"最大值為:"<<result[number][maxWeight]<<endl;system("pause");return 0; }Knapsack.h

#include<iostream> #include<cstring> #include<iomanip> using namespace std;//打印結果矩陣 template<class Type> void print(Type** m,int n,int c) {for(int i=0;i<n;i++){for(int j=0;j<c;j++){cout<<setw(5)<<m[i][j];}cout<<endl;} }//初始化結果矩陣 template<class Type> void inItResult(Type** result,int n,int c) {for(int i=0;i<n;i++){for(int j=0;j<c;j++){result[i][j]=0;}} }//動態規劃算法 template<class Type> void myKnapsack(Type *v,int* w,int c,int n,Type** m) {for(int i=1;i<n+1;i++){for(int j=1;j<c+1;j++){if(w[i-1]<=j){if(v[i-1]+m[i-1][j-w[i-1]]<m[i-1][j])m[i][j]=m[i-1][j];else m[i][j]=v[i-1]+m[i-1][j-w[i-1]];}else{m[i][j]=m[i-1][j];}}}}


轉載于:https://www.cnblogs.com/wizholy/archive/2012/10/21/2742797.html

總結

以上是生活随笔為你收集整理的C++实现动态规划算法之解决0-1背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。