USACO Section 1.3 : Mixing Milk
# include <stdio.h>
int p[5001],a[5001];
int qsort (int lx,int rx)
{
int i,j,pi,ai;
i=lx,j=rx,pi=p[i],ai=a[i];
do
{
while ((p[j]>pi)&&(i<j)) j--;
if (i<j)
{
p[i]=p[j],a[i]=a[j];
i++;
}
while ((p[i]<pi)&&(i<j)) i++;
if (i<j)
{
p[j]=p[i],a[j]=a[i];
j--;
}
}while (i<j);
p[i]=pi;
a[i]=ai;
i++;
j--;
if (i<rx) qsort(i,rx);
if (j>lx) qsort(lx,j);
return (0);
}
main ()
{
FILE *in=fopen("milk.in","r");
FILE *out=fopen("milk.out","w");
int N,M;
int i,j,min=0;
fscanf(in,"%d%d",&N,&M);
for (i=1;i<=M;i++)
fscanf (in,"%d%d",&p[i],&a[i]);
qsort(1,M);
for (i=1;(i<=M)&&(N>=0);i++)
{
if (N>=a[i])
{
min+=a[i]*p[i];
N-=a[i];
}
else
{
min+=N*p[i];
N=0;
}
}
fprintf (out,"%d\n",min);
fclose(in);
fclose(out);
exit(0);
}
int p[5001],a[5001];
int qsort (int lx,int rx)
{
int i,j,pi,ai;
i=lx,j=rx,pi=p[i],ai=a[i];
do
{
while ((p[j]>pi)&&(i<j)) j--;
if (i<j)
{
p[i]=p[j],a[i]=a[j];
i++;
}
while ((p[i]<pi)&&(i<j)) i++;
if (i<j)
{
p[j]=p[i],a[j]=a[i];
j--;
}
}while (i<j);
p[i]=pi;
a[i]=ai;
i++;
j--;
if (i<rx) qsort(i,rx);
if (j>lx) qsort(lx,j);
return (0);
}
main ()
{
FILE *in=fopen("milk.in","r");
FILE *out=fopen("milk.out","w");
int N,M;
int i,j,min=0;
fscanf(in,"%d%d",&N,&M);
for (i=1;i<=M;i++)
fscanf (in,"%d%d",&p[i],&a[i]);
qsort(1,M);
for (i=1;(i<=M)&&(N>=0);i++)
{
if (N>=a[i])
{
min+=a[i]*p[i];
N-=a[i];
}
else
{
min+=N*p[i];
N=0;
}
}
fprintf (out,"%d\n",min);
fclose(in);
fclose(out);
exit(0);
}