/* Problem 6--Flooded!
   This isn't too bad; just flood the lowest elevation first, and raise
   the level with each next higher elevation.  It turns out the grid
   structure is irrelevant to the problem. */
#include <stdio.h>
#include <stdlib.h>

FILE *in, *out;
int wl[900];

int main (int argc, char **argv);
int icmp (const void *a, const void *b);

int main (int argc, char **argv) {

  int m,n, i, j, ct, r=0, vol, diff;
  double level;

 in = fopen ("prob6.in","r");
 out = fopen ("prob6.out","w");
 while (fscanf (in,"%d %d",&m,&n),m !=0 || n != 0) {
  for (ct=i=0; i < m; i++) /* get info from file */
   for (j=0; j < n; j++)
    fscanf (in,"%d",&wl[ct++]);
  qsort (wl,ct,sizeof (int),icmp); /* sort by elevation */
  fscanf (in,"%d",&vol);
  level = wl[0];
  for (i=0; i < ct-1; i++) { /* how much do we need to flood this */
   diff = (wl[i+1]-wl[i])*100*(i+1); /* square? */
   if (diff < vol) { /* If there's enough, we raise the level */
    vol -= diff;
    level+= wl[i+1]-wl[i];
   } else { /* otherwise we stop */
    level+=vol/(100.0*(i+1));
    vol = 0;
    break;
   }
  }
  level += vol/(100.0*ct); /* add the remaining water to the system */
  fprintf (out,"Region %d\n",++r);
  fprintf (out,"Water level is %.2f meters.\n",level);
  fprintf (out,"%.2f percent of the region is under water.\n\n",
               100.0*(i+1)/ct);
 }
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}

/* compares two integers */
int icmp (const void *a, const void *b) {

 return *(int *)a - *(int *)b;
}
