10137 - The Trip

题目

10137 - The Trip
Time limit: 3.000 seconds

A number of students are members of a club that travels annually to exotic 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 have them share every expense as it occurs. So individuals in the group pay for particular things, like meals, hotels, taxi rides, plane tickets, etc. 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 a cent) all the students’ costs.

Input
Standard input will contain the information for several trips. The information for each trip consists of a line containing a positive integer, n, the number of students on the trip, followed by n lines of input, each containing the amount, in dollars and cents, spent by a student. 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

解题思路

  1. 当不能整除时,多的cent分配给那些本来就出得多的人
  2. 因为题目明确指出,输入数据有并且一定有两位小数,所以我将money扩大了100倍,变成整除来运算
  3. n是人数,时间复杂度和空间复杂度均为Θ(n)

通过代码

#include
#include  
int money[1005];

int main(){
    int n;
    int sum;
    int average;
    int exchange;

    char str[10];

#ifdef DEBUG
    freopen("in","r",stdin);
    freopen("out","w",stdout);
#endif

    while(true){
        scanf("%d\n",&n);
        if(n==0)
            break;

        sum=0;
        for(int i=0;i"%s",str);
            int j=strlen(str)-1;
            money[i]=str[j]-'0'+(str[j-1]-'0')*10;
            int tmp;
            sscanf(str,"%d",&tmp);  
            money[i]+=tmp*100;  
            sum+=money[i];
        }

        average=sum/n;      
        exchange=0;
        int back=0;
        for(int i=0;iif(money[i]>average){
                ++back;
                exchange+=(money[i]-average);
            }

        int remain=sum%n;
        exchange-=back"$%.2f\n",exchange/100.0);
    }
    return 0;
}

运行截图

10137 - The Trip_第1张图片

我的发现

double a=1.23;
int b=a*100;

b等于多少呢?123吗?答案是不一定,有可能是122,这就是浮点数运算中的精度问题。

你可能感兴趣的:(算法,usaco,uva,C)