Knapsack problem solve in CPP

Knapsack problem is very well-known problem. Here goes the solution in CPP. I would be glad if it comes in any good to you 🙂

#include
#include
#include
//ml;
class sack
{
	int *weight;
	int *profit;
	int ans1,ans2,m;
	double vect[100];

public :
	
	sack(int no)
	{
		weight=new int [no];
		profit=new int [no];
		for(int i=0;i<no;i++)
		{
			weight[i]=0;
			profit[i]=0;
		}
	}
	void getinp(int no)
	{
		for(int i=0;i<no;i++)
		{
			cout<<"Enter the "<<i+1<>weight[i];
			cout<<endl;
		}
		for(int j=0;j<no;j++)
		{
			cout<<"Enter the "<<j+1<>profit[j];
			cout<<endl;
		}
		cout<<"Enter the size of knapsack ::"<>m;

	}

	void sort(int no)
	{
		for(int i=0;i<no;i++)
			for(int j=0;jweight[j+1])
					swap(weight[j],weight[j+1]);
				if(profit[j]>profit[j+1])
					swap(profit[j],profit[j+1]);
			}
	}


	void kanp(int n)
		{
		int i=0;
		for(i=0;i<=n;i++)
			vect[i]=0;
		double u=m;
		for(i=0;iu)
				break;
			vect[i]=1;
			u=u-weight[i];
		}
		if(i<=n)
			vect[i]=u/weight[i];
		
	}

	void swap(int &a,int &b)
	{
		int temp=a;
		a=b;
		b=temp;
	}
	void output(int y)
	{
		for(int i=0;i<y;i++)
			cout<<weight[i]<<"\t";
		cout<<endl;
		for(i=0;i<y;i++)
			cout<<profit[i]<<"\t";
		cout<<endl;
		for(i=0;i<y;i++)
			cout<<vect[i]<<"\t";
		cout<<endl;
	}

};

int main()
{
	int objno;
	cout<<"Enter the number of object :\n"<>objno;
	sack obj(objno);
	obj.getinp(objno);
	obj.sort(objno);
	obj.kanp(objno-1);
	obj.output(objno);
	return 1;
}
	

One thought on “Knapsack problem solve in CPP

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s