Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

//slip-17

q1]

#include<stdio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
for(i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}

return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\n\nSolution #%d:\n",count);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf(" Q\t");
else
printf("* \t");
}
printf("\n");
}
}
void queen(int n)
{
int k=1;
a[k]=0;
while(k!=0)
{
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
}
else
k--;
}
}
void main()
{
int i,n;
printf("Enter the number of queens \n");
scanf("%d",&n);
queen(n);
printf("\n Total solutions %d",count);

}
_______________________________________________________
q2]

#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int count=0;

int i,j,n;
printf("Enter the number of items:");
scanf("%d",&n);

for(i=0;i<n;i++)
{
count++;
printf("Enter the weight and profit for item[%d] :\n",i);
scanf("%f %f",&weight[i],&profit[i]);
}
printf("Enter the capacity of knapsack :\n");
scanf("%f",&capacity);

for(i=0;i<n;i++)
{
count++;
ratio[i]= profit[i]/weight[i];
}
for(i=0;i<n;i++)
{
count++;
for(j=i+1;j<n;j++)
{
count++;
if(ratio[i] <ratio[j])
{
count++;
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;

temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;

temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
}
}

printf("knapsack problem using greedy algorithm :\n");


for(i=0;i<n;i++)
{
count++;
if(weight[i] >capacity)
{
count++;
break;
}
else
{
count++;
Totalvalue=Totalvalue+ profit[i];
capacity=capacity-weight[i];
}
}
if(i<n)
count++;
Totalvalue=Totalvalue+(ratio[i]*capacity);
printf("The maximum profit value is: %f\n",Totalvalue);

printf("Number of count steps are: %d\n",count);


return 0;
}

You might also like