mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-13 16:59:50 +08:00
knaspsack dynamic
This commit is contained in:
@@ -1,8 +1,35 @@
|
||||
//0-1 Knapsack problem - Dynamic programming
|
||||
#include <bits/stdc++.h>
|
||||
//#include <bits/stdc++.h>
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
//void Print(int res[20][20], int i, int j, int capacity)
|
||||
//{
|
||||
// if(i==0 || j==0)
|
||||
// {
|
||||
// return;
|
||||
// }
|
||||
// if(res[i-1][j]==res[i][j-1])
|
||||
// {
|
||||
// if(i<=capacity)
|
||||
// {
|
||||
// cout<<i<<" ";
|
||||
// }
|
||||
//
|
||||
// Print(res, i-1, j-1, capacity-i);
|
||||
// }
|
||||
// else if(res[i-1][j]>res[i][j-1])
|
||||
// {
|
||||
// Print(res, i-1,j, capacity);
|
||||
// }
|
||||
// else if(res[i][j-1]>res[i-1][j])
|
||||
// {
|
||||
// Print(res, i,j-1, capacity);
|
||||
// }
|
||||
//}
|
||||
|
||||
int Knapsack(int capacity,int n,int weight[],int value[]){
|
||||
int res[n+1][capacity+1];
|
||||
int res[20][20];
|
||||
for (int i = 0; i < n+1; ++i)
|
||||
{
|
||||
for (int j = 0; j < capacity+1; ++j)
|
||||
@@ -15,9 +42,11 @@ int Knapsack(int capacity,int n,int weight[],int value[]){
|
||||
res[i][j] = res[i-1][j];
|
||||
}
|
||||
}
|
||||
// Print(res, n, capacity, capacity);
|
||||
// cout<<"\n";
|
||||
return res[n][capacity];
|
||||
}
|
||||
int main(int argc, char const *argv[])
|
||||
int main()
|
||||
{
|
||||
int n;
|
||||
cout<<"Enter number of items: ";
|
||||
@@ -38,4 +67,4 @@ int main(int argc, char const *argv[])
|
||||
cin>>capacity;
|
||||
cout<<Knapsack(capacity,n,weight,value);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
BIN
Dynamic Programming/Knapsack.exe
Normal file
BIN
Dynamic Programming/Knapsack.exe
Normal file
Binary file not shown.
Reference in New Issue
Block a user