USACO Section 1.3 : Barn Repair
# include <stdio.h>
int num[201]={0},f[202]={0};
int qsort (int lx,int rx,int s[201])
{
int i,j,t;
i=lx,j=rx,t=s[i];
do
{
while ((s[j]>t)&&(i<j)) j--;
if (i<j)
{
s[i]=s[j];
i++;
}
while ((s[i]<t)&&(i<j)) i++;
if (i<j)
{
s[j]=s[i];
j--;
}
}while (i<j);
s[i]=t;
i++;
j--;
if (i<rx) qsort(i,rx,s);
if (j>lx) qsort(lx,j,s);
return (0);
}
main ()
{
FILE *in=fopen ("barn1.in","r");
FILE *out=fopen("barn1.out","w");
int M,S,C;
int maxf=0;
int i;
fscanf (in,"%d%d%d",&M,&S,&C);
for (i=1;i<=C;i++)
fscanf (in,"%d",&num[i]);
qsort(1,C,num);
for (i=2;i<=C;i++)
f[i]=num[i]-num[i-1]-1;
qsort(1,C,f);
for (i=C;i>C-M+1;i--)
maxf+=f[i];
maxf+=num[1]-1;
maxf+=S-num[C];
fprintf (out,"%d\n",S-maxf);
fclose(in);
fclose(out);
exit(0);
}
int num[201]={0},f[202]={0};
int qsort (int lx,int rx,int s[201])
{
int i,j,t;
i=lx,j=rx,t=s[i];
do
{
while ((s[j]>t)&&(i<j)) j--;
if (i<j)
{
s[i]=s[j];
i++;
}
while ((s[i]<t)&&(i<j)) i++;
if (i<j)
{
s[j]=s[i];
j--;
}
}while (i<j);
s[i]=t;
i++;
j--;
if (i<rx) qsort(i,rx,s);
if (j>lx) qsort(lx,j,s);
return (0);
}
main ()
{
FILE *in=fopen ("barn1.in","r");
FILE *out=fopen("barn1.out","w");
int M,S,C;
int maxf=0;
int i;
fscanf (in,"%d%d%d",&M,&S,&C);
for (i=1;i<=C;i++)
fscanf (in,"%d",&num[i]);
qsort(1,C,num);
for (i=2;i<=C;i++)
f[i]=num[i]-num[i-1]-1;
qsort(1,C,f);
for (i=C;i>C-M+1;i--)
maxf+=f[i];
maxf+=num[1]-1;
maxf+=S-num[C];
fprintf (out,"%d\n",S-maxf);
fclose(in);
fclose(out);
exit(0);
}