Sie sind auf Seite 1von 11

Backtracking

#include <stdio.h>

#include <conio.h>

#define MAX 20

float final_profit;

int w[MAX];

int p[MAX];

int n,m;

int temp[MAX],x[MAX];

float final_wt;

float Bound_Calculation(int,int,int);

void BackTracking(int,int,int);

void main()

int i;

clrscr();

printf("\n-------------------------------------------------------");

printf("\n KNAPSACK PROBLEM USING BACKTRACKING");

printf("\n-------------------------------------------------------");

printf("\n Enter number of Objects you want:");

scanf("%d",&n);

printf("\n-------------------------------------------------------");

for(i=1;i<=n;i++)

printf("\n Enter Weight and value for object%d:",i);

scanf("%3d %3d",&w[i],&p[i]);

printf("\n Enter Capacity of Knapsack:");


scanf("%d",&m);

getch();

printf("\n-------------------------------------------------------");

printf("\n Weight\tProfit");

printf("\n-------------------------------------------------------");

for(i=1;i<=n;i++)

printf("\n %d \t %d",w[i],p[i]);

BackTracking(1,0,0);

printf("\n-------------------------------------------------------");

printf("\n Following Objects are included:");

printf("\n-------------------------------------------------------");

for(i=1;i<=n;i++)

if(x[i]==1)

printf("\n%d",i);

printf("\n-------------------------------------------------------");

printf("\n Final Weight:%0.2f",final_wt);

printf("\n Final Profit:%0.2f",final_profit);

getch();

float Bound_Calculation(int cp,int cw,int k)

int ub,c,i;

ub=cp;

c=cw;
for(i=k+1;i<=n;i++)

c=c+w[i];

if(c < m)

ub=ub+p[i];

else

return (ub+(1-(c-m)/w[i])*p[i]);

return ub;

void BackTracking(int k,int cp,int cw)

int new_k,new_cp,new_cw,j;

if(cw+w[k]<=m)

temp[k]=1;

if(k < n)

new_k=k+1;

new_cp=cp+p[k];

new_cw=cw+w[k];

BackTracking(new_k,new_cp,new_cw);

if((new_cp>final_profit)&&(k==n))

final_profit=new_cp;

final_wt=new_cw;

for(j=1;j<=k;j++)

x[j]=temp[j];

}
}

if(Bound_Calculation(cp,cw,k)>=final_profit)

temp[k]=0;

if(k < n)

BackTracking(k+1,cp,cw);

if((cp>final_profit)&&(k==n))

final_profit=cp;

final_wt=cw;

for(j=1;j<=n;j++)

x[j]=temp[j];

}
Enter number of Objects you want:4

-------------------------------------------------------
Enter Weight and value for object1:5 6

Enter Weight and value for object2:6 8

Enter Weight and value for object3:7 12

Enter Weight and value for object4:8 15

Enter Capacity of Knapsack:13

-------------------------------------------------------
Weight Profit
-------------------------------------------------------
5 6
6 8
7 12
8 15
-------------------------------------------------------
Following Objects are included:
-------------------------------------------------------
2
3
-------------------------------------------------------
Final Weight:13.00
Final Profit:20.00
Greedy technique

#include<stdio.h>
#include<time.h>
#include<conio.h>
void knapsack(float capacity, int n, float weight[], float profit[])
{
float x[20], totalprofit,y;
int i,j;
y=capacity;
totalprofit=0;
for(i=0;i < n;i++)
x[i]=0.0;
for(i=0;i < n;i++)
{
if(weight[i] > y)
break;
else
{
x[i]=1.0;
totalprofit=totalprofit+profit[i];
y=y-weight[i];
}
}
if(i < n)
x[i]=y/weight[i];
totalprofit=totalprofit+(x[i]*profit[i]);
printf("The selected elements are:-\n ");
for(i=0;i < n;i++)
if(x[i]==1.0)
printf("\nProfit is %f with weight %f ", profit[i], weigh
t[i]);
else if(x[i] > 0.0)
printf("\n%f part of Profit %f with weight %f", x[i], pro
fit[i], weight[i]);
printf("\nTotal profit for %d objects with capacity %f = %f\n\n", n, capa
city,totalprofit);
}
void main()
{
float weight[20],profit[20],ratio[20], t1,t2,t3;
int n;
time_t start,stop;
float capacity;
clrscr();
int i,j;
printf("Enter number of objects: ");
scanf("%d", &n);
printf("\nEnter the capacity of knapsack: ");
scanf("%f", &capacity);
for(i=0;i < n;i++)
{
printf("\nEnter %d(th) profit: ", (i+1));
scanf("%f", &profit[i]);
printf("Enter %d(th) weight: ", (i+1));
scanf("%f", &weight[i]);
ratio[i]=profit[i]/weight[i];
}
start=time(NULL);
for(i=0;i < n;i++)
for(j=0;j < n;j++)
{
if(ratio[i] > ratio[j])
{
t1=ratio[i];
ratio[i]=ratio[j];
ratio[j]=t1;
t2=weight[i];
weight[i]=weight[j];
weight[j]=t2;
t3=profit[i];
profit[i]=profit[j];
profit[j]=t3;
}
}
knapsack(capacity,n,weight,profit);
stop=time(NULL);
printf("\nKnapsack = %f\n", difftime(stop,start));
getch();
}
Enter number of objects: 5

Enter the capacity of knapsack: 10

Enter 1(th) profit: 9


Enter 1(th) weight: 6

Enter 2(th) profit: 15


Enter 2(th) weight: 3

Enter 3(th) profit: 20


Enter 3(th) weight: 2

Enter 4(th) profit: 8


Enter 4(th) weight: 4

Enter 5(th) profit: 10


Enter 5(th) weight: 3
The selected elements are:-

Profit is 20.000000 with weight 2.000000


Profit is 15.000000 with weight 3.000000
Profit is 10.000000 with weight 3.000000
0.500000 part of Profit 8.000000 with weight 4.000000
Total profit for 5 objects with capacity 10 = 49.000000

Knapsack = 0.000000
// C++ program to solve knapsack problem using
Branch and bound

// branch and bound


#include <bits/stdc++.h>
using namespace std;

// Stucture for Item which store weight and corresponding


// value of Item
struct Item
{
float weight;
int value;
};

// Node structure to store information of decision


// tree
struct Node
{
// level --> Level of node in decision tree (or index
// in arr[]
// profit --> Profit of nodes on path from root to this
// node (including this node)
// bound ---> Upper bound of maximum profit in subtree
// of this node/
int level, profit, bound;
float weight;
};

// Comparison function to sort Item according to


// val/weight ratio
bool cmp(Item a, Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}

// Returns bound of profit in subtree rooted with u.


// This function mainly uses Greedy solution to find
// an upper bound on maximum profit.
int bound(Node u, int n, int W, Item arr[])
{
// if weight overcomes the knapsack capacity, return
// 0 as expected bound
if (u.weight >= W)
return 0;

// initialize bound on profit by current profit


int profit_bound = u.profit;

// start including items from index 1 more to current


// item index
int j = u.level + 1;
int totweight = u.weight;

// checking index condition and knapsack capacity


// condition
while ((j < n) && (totweight + arr[j].weight <= W))
{
totweight += arr[j].weight;
profit_bound += arr[j].value;
j++;
}

// If k is not n, include last item partially for


// upper bound on profit
if (j < n)
profit_bound += (W - totweight) * arr[j].value /
arr[j].weight;

return profit_bound;
}

// Returns maximum profit we can get with capacity W


int knapsack(int W, Item arr[], int n)
{
// sorting Item on basis of value per unit
// weight.
sort(arr, arr + n, cmp);

// make a queue for traversing the node


queue<Node> Q;
Node u, v;

// dummy node at starting


u.level = -1;
u.profit = u.weight = 0;
Q.push(u);

// One by one extract an item from decision tree


// compute profit of all children of extracted item
// and keep saving maxProfit
int maxProfit = 0;
while (!Q.empty())
{
// Dequeue a node
u = Q.front();
Q.pop();

// If it is starting node, assign level 0


if (u.level == -1)
v.level = 0;

// If there is nothing on next level


if (u.level == n-1)
continue;

// Else if not last node, then increment level,


// and compute profit of children nodes.
v.level = u.level + 1;

// Taking current level's item add current


// level's weight and value to node u's
// weight and value
v.weight = u.weight + arr[v.level].weight;
v.profit = u.profit + arr[v.level].value;
// If cumulated weight is less than W and
// profit is greater than previous profit,
// update maxprofit
if (v.weight <= W && v.profit > maxProfit)
maxProfit = v.profit;

// Get the upper bound on profit to decide


// whether to add v to Q or not.
v.bound = bound(v, n, W, arr);

// If bound value is greater than profit,


// then only push into queue for further
// consideration
if (v.bound > maxProfit)
Q.push(v);

// Do the same thing, but Without taking


// the item in knapsack
v.weight = u.weight;
v.profit = u.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit)
Q.push(v);
}

return maxProfit;
}

// driver program to test above function


int main()
{
int W = 10; // Weight of knapsack
Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100},
{5, 95}, {3, 30}};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum possible profit = "


<< knapsack(W, arr, n);

return 0;
}

Output :
Maximum possible profit = 235

Das könnte Ihnen auch gefallen