/* Problem 8--Making A Budget
   This wasn't too bad.  This solution just chugs through the data.
   Note that "cost" begins with a lowercase "c" in this program.
   There was a typo in the problem description. */

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv);
int min (int a, int b);
int max (int a, int b);

int main (int argc, char **argv) {

  FILE *in, *out;
  int m, hire, sal, sev, T[24], i, k, cs, cost, emp, nemp, keep;

 in = fopen ("prob8.in","r");
 out = fopen ("prob8.out","w");
 for (cs=1;fscanf (in,"%d",&m),m>0;cs++) {/* read # of months */
  fscanf (in,"%d %d %d",&hire, &sal, &sev); /* get payment stuff */
  for (i=0;i<m;i++) fscanf (in,"%d",&T[i]); /* get employee schedule */
  keep = (hire+sev)/sal; /* how many months can we retain an extra */
  cost = (hire+sal)*T[0];/* initial cost */
  emp = T[0];
  for (i=1;i<m;i++) {
     /* For each month, compute how many temps we will need */
   nemp = T[i]; /* What is the largest # of employees we will need */
   for (k=i+1;k<min (m,i+keep+1);k++)  /* over the retaining period */
    nemp = max (nemp,T[k]);
   nemp = max (T[i],min (emp,nemp)); /* Keep as many as we have */
     /* Compute new cost information */
   if (emp > nemp) cost += (emp-nemp)*sev;
   else if (nemp > emp) cost += (nemp-emp)*hire;
   cost += nemp*sal; /* Pay the employees */
   emp = nemp;
  }
  fprintf (out,"Case %d, cost = $%d\n",cs,cost);
 }
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}

/* Computes the minimum of two integers. */

int min (int a, int b) {

 return a < b ? a : b;
}

/* Computes the maximum of two integers. */

int max (int a, int b) {

 return a > b ? a : b;
}
