Vinícius Oliveira

I love coding.

Programming Challenges - the Trip

Problem The Trip

A group of students are members of a club that travels annually to different lo- cations. Their destinations in the past have included Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta. This spring they are planning a trip to Eindhoven.
The group agrees in advance to share expenses equally, but it is not practical to share every expense as it occurs.
Thus individuals in the group pay for particular things, such as meals, hotels, taxi rides, and plane tickets. After the trip, each student’s expenses are tallied and money is exchanged so that the net cost to each is the same, to within one cent. In the past, this money exchange has been tedious and time consuming.
Your job is to compute, from a list of expenses, the minimum amount of money that must change hands in order to equalize (within one cent) all the students’ costs.

Input

Standard input will contain the information for several trips. Each trip consists of a
line containing a positive integer n denoting the number of students on the trip. This is
followed by n lines of input, each containing the amount spent by a student in dollars
and cents. There are no more than 1000 students and no student spent more than
$10,000.00. A single line containing 0 follows the information for the last trip.

Output

For each trip, output a line stating the total amount of money, in dollars and cents,
that must be exchanged to equalize the students’ costs.

Solution

(the_trip.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>

using namespace std;

#define MAX_STUDENT 1000

double student_spent[MAX_STUDENT];
double total_high = 0.0;
double total_low = 0.0;

double sum (int n){
  double result = 0;
  for (int i = 0; i < n; i++){
      result += student_spent[i];
  }
  return result;
}

int main (){
  int  n;
  while (scanf ("%d",&n) != EOF  && n!=0){
      for (int i = 0; i < n; i++){
          scanf ("%lf",&student_spent[i]);
      }
      double avg = sum(n)/n;
      for (int i = 0; i < n; i++){
          double result = student_spent[i] - avg;
          if (result >= 0) total_high+= floor(result*100)/100;
          else total_low -= ceil(result*100)/100;
      }
      printf("$%.2f\n",max(total_low,total_high));
      total_high = 0;
      total_low = 0;
  }
  return 0;
}