I have the following solution for the Trip problem from Skiena's and Revilla's Programming Challenges (full problem description here).
//#include "stdafx.h"
#include <iostream>
#include <string> //Always import <string> if piping std input to a string in .net
#include<algorithm>
#include<math.h>
#include<fstream>
using namespace std;
int main()
{
//ofstream myfile;
//myfile.open("example.txt");
int n; //number of students sharing trip costs.
while (cin >> n) {
if (n == 0) {
return 0;
}
double *ammounts_spent = new double[n];
double total_spent = 0;
for (int i = 0; i < n; i++) {
cin >> ammounts_spent[i];
total_spent += ammounts_spent[i];
}
double ammount_exchanged = 0;
double ammount_exchanged_below = 0;
double ammount_exchanged_above = 0;
double average_spent = total_spent / n;
double rounded_down_average_spent =(double)((int)(average_spent * 100)/(double)100);
double rounded_up_average_spent = rounded_down_average_spent + 0.01;
if (rounded_down_average_spent - average_spent < 0) {
for (int i = 0; i < n; i++) {
if (average_spent > ammounts_spent[i]) {
ammount_exchanged_below += rounded_down_average_spent - ammounts_spent[i];
}
else {
ammount_exchanged_above += ammounts_spent[i] - rounded_up_average_spent;
}
}
}
else {
for (int i = 0; i < n; i++) {
if (average_spent > ammounts_spent[i]) {
ammount_exchanged_below += average_spent - ammounts_spent[i];
}
else {
ammount_exchanged_above += ammounts_spent[i] -average_spent;
}
}
}
ammount_exchanged = max(ammount_exchanged_above, ammount_exchanged_below);
if (ammount_exchanged == floor(ammount_exchanged)) {
cout << "$" << ammount_exchanged << ".00\n";
}
else {
cout << "$" << ammount_exchanged << "\n";
}
}
}
It works for all debug input given on udebug and even for tricky instances such as
> 4
> 1.01
> 1.01
> 1.00
> 1.00
Where the amount exchanged is $0.00. Yet the UVA online judge is giving me a verdict of wrong answer.
ammount
should be spelledamount
" is usually OK. \$\endgroup\$