UVa 10137 The Trip

引用某個解題者的話:This problem IS a trip.

乍看很簡單,但是很容易在浮點數精確度上吃悶虧。
最後我全部轉成int來運算,確保一切在掌握之內。

兩點提醒
1. 平均開銷算出來以後要四捨五入到小數第二位(1 cent)
2. 因為平均開銷不精確,所以exchange amount 要統計兩個,輸出小的那一個。

/**
* UVa 10137 (AC)
* Author: chchwy
* Last Modified: 2009.03.26
*/
#include<iostream>
/* read expense as cent. ex. 1.23 dollar => 123 cent */
int getExpense()
{
int i = 0;
char c;
char buf[16];
while ((c = getchar()) != '\n')
{
if (c != '.')
buf[i++] = c;
}
buf[i] = 0;
return atoi(buf);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("10137.in", "r", stdin);
//freopen("10137.out","w",stdout);
#endif
int stu[1000]; //expense of each student
int stuNum; //number of students
/* for each case */
while (scanf("%d ", &stuNum) == 1)
{
if (stuNum == 0) break;
//compute the average
int sum = 0;
for (int i = 0; i < stuNum; ++i)
{
stu[i] = getExpense();
sum += stu[i];
}
int avg = ((double)sum / stuNum) + 0.5;
//compute the exchange amount
int exchg1 = 0, exchg2 = 0;
for (int i = 0; i < stuNum; ++i)
{
if (stu[i] > avg)
exchg1 += stu[i] - avg;
else if (stu[i] < avg)
exchg2 += avg - stu[i];
}
double rslt = (exchg1 < exchg2) ? exchg1 : exchg2;
rslt /= 100;
printf("$%.2lf\n", rslt);
}
return 0;
}
view raw 10137.cpp hosted with ❤ by GitHub

留言

這個網誌中的熱門文章

UVa 10125 Sumsets

讀書心得: 撒哈拉的故事

讀書心得: 你以為你以為的就是你以為的嗎?