A solution for "The Trip" problem
Problem description:
http://icpcres.ecs.baylor.edu/onlinejudge/external/101/10137.html
Author: Joana Matos Fonseca da Trindade
Date: 2008.03.08
1 2 /* 3 * A solution for "The Trip" problem. 4 * UVa ID: 10137 5 */ 6 #include <stdio.h> 7 8 int main (int argc, const char * argv[]) { 9 /* number of students in the trip */ 10 long numOfStudents; 11 12 /* the total sum of money spent */ 13 double total; 14 15 /* the total amount of money to exchange in order to equalize */ 16 double exchange; 17 18 /* the equalized trip amount to be payed by each student */ 19 double equalizedAmount; 20 21 /* difference between the equalized amount and the amount spent */ 22 double diff; 23 24 /* sum of all negative differences */ 25 double negativeSum; 26 27 /* sum of all positive differences */ 28 double positiveSum; 29 30 /* iterator */ 31 int i; 32 33 while(scanf("%ld", &numOfStudents) != EOF) { 34 35 /* 0, ends the program */ 36 if (!numOfStudents) { 37 return 0; 38 } 39 40 /* keeps the amount of money spent by each student */ 41 double amountSpent[numOfStudents]; 42 43 /* clean */ 44 total = 0; 45 negativeSum = 0; 46 positiveSum = 0; 47 48 for (i = 0; i < numOfStudents; i++) { 49 scanf("%lf\n", &amountSpent[i]); 50 total += amountSpent[i]; 51 } 52 53 equalizedAmount = total / numOfStudents; 54 55 for (i = 0; i < numOfStudents; i++) { 56 /* to ensure 0.01 precision */ 57 diff = (double) (long) ((amountSpent[i] - equalizedAmount) * 100.0) / 100.0; 58 59 if (diff < 0) { 60 negativeSum += diff; 61 } else { 62 positiveSum += diff; 63 } 64 } 65 66 /* when the total amount is even, these sums do not differ. otherwise, they differ in one cent */ 67 exchange = (-negativeSum > positiveSum) ? -negativeSum : positiveSum; 68 69 /* output result */ 70 printf("$%.2lf\n", exchange); 71 } 72 73 return 0; 74 }