Tuesday, May 19, 2009

C Sharp Queries

Anyone Who has Any Problem related to code(Syntax) in C Sharp or any other Language can leave their query and it will be solved as early as possible.

Knapsack Problem 0-1

void PRINT_01(int**,int*,int*,int,int);

void main()
{
clrscr();
int i,w;
cout<<"Enter No. Of Items : ";
int n;
cin>>n;
int *p,*q;
p=new int[n+1];
q=new int[n+1];
for(i=1;i<=n;i++)
{
cout<<"Enter Weigth : ";
cin>>q[i];
cout<<"Enter Profit : ";
cin>>p[i];
}
cout<<"\nEnter Maximum Weight : ";
int W;
cin>>W;
int **B;
B=new int*[W];
for(w=0;w<=W;w++);
B[w]=new int[n+1];

for(w=0;w<=W;w++)
B[0][w]=0;
for(i=0;i<=n;i++)
B[i][0]=0;

for(i=1;i<=n;i++)
{
for(w=1;w<=W;w++)
{
if(q[i]<=w) // item i can be part of the solution
if((p[i] + B[i-1][w-q[i]])>B[i-1][w])
B[i][w]=(p[i] + B[i-1][w-q[i]]);
else
B[i][w]=B[i-1][w];
else
B[i][w]=B[i-1][w]; // wi > w
}
}
for(w=0;w<=W;w++)
{
for(i=0;i<=n;i++)
cout< cout<<"\n";
}
cout<<"\n\n";
cout<<"Item No. Selected\tWeigth\tProfit\n\n";
PRINT_01(B,q,p,n,W);
cout<<"Total Profit : "< getch();
}

void PRINT_01(int **B,int *Q,int *P,int i,int w)
{
if(i==0||w==0)
return;
if(B[i-1][w]!=B[i][w])
{
PRINT_01(B,Q,P,i-1,w-Q[i]);
cout<<"\t"< }
else
PRINT_01(B,Q,P,i-1,w);
}