USACO Section 1.2 : Milking Cows
# include <stdio.h>
long begin[5001],end[5001];
long maxw=0,maxf=0;
long lastend;
long max (long x,long y)
{
if (x>y) return (x);
else return (y);
}
long qsort (long lx,long rx)
{
long i,j,tb,te;
i=lx;
j=rx;
tb=begin[lx];
te=end[lx];
do
{
while ((begin[j]>tb)&&(j>i))
j--;
if (i<j)
{
begin[i]=begin[j];
end[i]=end[j];
i++;
}
while ((begin[i]<tb)&&(j>i))
i++;
if (i<j)
{
begin[j]=begin[i];
end[j]=end[i];
j--;
}
}while (i<j);
begin[i]=tb;
end[i]=te;
i++;
j--;
if (j>lx) qsort(lx,j);
if (i<rx) qsort(i,rx);
return (0);
}
main ()
{
FILE *in=fopen("milk2.in","r");
FILE *out=fopen("milk2.out","w");
long N;
long i,j;
fscanf (in,"%d",&N);
for (i=1;i<=N;i++)
fscanf (in,"%d%d",&begin[i],&end[i]);
qsort(1,N);
for (i=1;i<N;i++)
{
for (j=i+1;j<=N;j++)
if ((end[i]>=begin[j])&&(end[i]<=end[j]))
end[i]=end[j];
}
for (i=1;i<=N;i++)
maxw=max(maxw,end[i]-begin[i]);
for (i=2;i<=N;i++)
{
lastend=0;
for (j=1;j<i;j++)
{
lastend=max(lastend,end[j]);
}
maxf=max(maxf,begin[i]-lastend);
}
fprintf (out,"%d %d\n",maxw,maxf);
fclose(in);
fclose(out);
exit(0);
}
long begin[5001],end[5001];
long maxw=0,maxf=0;
long lastend;
long max (long x,long y)
{
if (x>y) return (x);
else return (y);
}
long qsort (long lx,long rx)
{
long i,j,tb,te;
i=lx;
j=rx;
tb=begin[lx];
te=end[lx];
do
{
while ((begin[j]>tb)&&(j>i))
j--;
if (i<j)
{
begin[i]=begin[j];
end[i]=end[j];
i++;
}
while ((begin[i]<tb)&&(j>i))
i++;
if (i<j)
{
begin[j]=begin[i];
end[j]=end[i];
j--;
}
}while (i<j);
begin[i]=tb;
end[i]=te;
i++;
j--;
if (j>lx) qsort(lx,j);
if (i<rx) qsort(i,rx);
return (0);
}
main ()
{
FILE *in=fopen("milk2.in","r");
FILE *out=fopen("milk2.out","w");
long N;
long i,j;
fscanf (in,"%d",&N);
for (i=1;i<=N;i++)
fscanf (in,"%d%d",&begin[i],&end[i]);
qsort(1,N);
for (i=1;i<N;i++)
{
for (j=i+1;j<=N;j++)
if ((end[i]>=begin[j])&&(end[i]<=end[j]))
end[i]=end[j];
}
for (i=1;i<=N;i++)
maxw=max(maxw,end[i]-begin[i]);
for (i=2;i<=N;i++)
{
lastend=0;
for (j=1;j<i;j++)
{
lastend=max(lastend,end[j]);
}
maxf=max(maxf,begin[i]-lastend);
}
fprintf (out,"%d %d\n",maxw,maxf);
fclose(in);
fclose(out);
exit(0);
}