Problem C: The Trip
Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 19 Solved: 3
[Submit][Status][Web Board]
Description
The Trip A group of students are members of a club that travels annually to different locations. 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.
Sample Input
3 10.00 20.00 30.00 4 15.00 15.01 3.00 3.01 0
Sample Output
$10.00 $11.99
HINT
卡在这道题上好久,总有几组测试数据不通过。
遂参考了一份网上的结题报告。
下面是Rainy Days的博客上这道题的代码,这是位牛人,粗算已经做过700+的题,佩服,向前辈学习!
http://www.cnblogs.com/rainydays/archive/2011/07/07/2100471.html
下面是我对他的代码的理解,说实话,看别人代码果然能开拓视野,提高自己的水平。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cmath> 6 #include <algorithm> 7 using namespace std; 8 9 #define maxn 1005 10 11 int n; 12 long long sum, f[maxn], f1[maxn]; 13 14 int main() 15 { 16 //freopen("t.txt", "r", stdin); 17 while (scanf("%d", &n), n) 18 //第一次看到这种写法,括号里面是一个逗号表达式,逗号表达式的值和类型是最后一个表达式的值和类型。另注意和while(scanf("%d",&n) && n)的区别。 19 { 20 sum = 0; 21 for (int i = 0; i < n; i++) 22 { 23 double a; 24 scanf("%lf", &a); 25 f[i] = (long long)(a * 100 + 0.5); 26 sum += f[i]; 27 } 28 sort(f, f + n); 29 reverse(f, f + n); 30 long long a, ave; 31 ave = sum / n; 32 a = sum % n; 33 for (int i = 0; i < n; i++) 34 f1[i] = ave; 35 for (int i = 0; i < a; i++) 36 f1[i] += 1; 37 long long ans = 0; 38 for (int i = 0; i < n; i++) 39 if (f[i] > f1[i]) 40 ans += f[i] - f1[i]; 41 printf("$%.2f\n", double(ans / 100.0)); 42 } 43 return 0; 44 }