During a competition I came across a problem which at that time I was unable to solve.
But now I have developed a code for that problem. Now I request you people to please better up my logic since in this code the logic is too complex, although it is working correctly.
the problem is:
On the wrapper of a bar of chocolate, the specified amount of componenets must be in NON_INCREASING order. Means
Water 50%
Taurine 30%
Lime
is likely to be true, but
Water
Cocoa-butter
cocoa-powder 40%
Lecithine
is absolutely wrong.
Now the task is to write a program that determines whether an inscription of components on a chocolate bar.
the input file contains the number of components N(1<=N<=5000). each of the following lines contains the descriptions of one component. each description contain a non-spaced name of component. then there is a space followed by a number 1 or 0. 1 if the % of the component is given and zero if the percentage of component is not given.
A number 00 indicates the end of input file.
Following is the code:
Code:
#include<stdio.h>
void checkarr(int *,int);
int main()
{
FILE *fp;
int *amnt,i,flag=0,n;
char *name;
fp=fopen("prob1.txt","r");
if(fp==NULL)
{
printf("Error opening file");
exit(1);
}
fscanf(fp,"%d",&n);
while(n!=0)
{
free(amnt);
amnt=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
fscanf(fp,"%s%d",name,&flag);
if(flag==0)
amnt[i]=-1;
else
fscanf(fp,"%d",&amnt[i]);
}
checkarr(amnt,n);
fscanf(fp,"%d",&n);
}
fclose(fp);
return 0;
}
void checkarr(int *amnt,int n)
{
int flag=0;
int i,sum=0,temp=0;
for(i=n-1;i>=0;i++)
{
if(amnt[i]==-1)
amnt[i]=temp;
else
temp=amnt[i];
}
for(i=0;i<n;i++)
{
sum=sum+amnt[i];
if(amnt[i]<amnt[i+1])
{
flag=0;
break;
}
flag=1;
}
if(sum>100)
flag=0;
if(flag==0)
printf("NO\n");
else
printf("YES\n");
}
the output of the attached file must be:
NO
YES
NO