I convert all the calculations from floating-point to integral to avoid all the messes in floating-point calculation. The method is straight forward: I simulate the exchanging progress and use a 'budget' to record the extra cents that should be exchanged to keep the costs in balance.
Code:
- /*************************************************************************
- * Copyright (C) 2008 by liukaipeng *
- * liukaipeng at gmail dot com *
- *************************************************************************/
- /* @JUDGE_ID 00000 10137 C "The Trip" */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <strings.h>
- #define MAX 1000
- int calc_exchange(int costs[], int persons)
- {
- int total = 0, aver, exchange, budget;
- int i;
- for (i = 0; i < persons; ++i)
- total += costs[i];
- aver = total / persons;
- exchange = 0;
- budget = 0;
- if (total % persons != 0)
- aver += 1;
- for (i = 0; i < persons; ++i) {
- if (costs[i] >= aver) {
- exchange += costs[i] - aver;
- budget += costs[i] - aver;
- } else if (costs[i] < aver - 1) {
- budget -= aver - 1 - costs[i];
- }
- }
- if (budget < 0)
- exchange -= budget;
- return exchange;
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- char in[256];
- char out[256];
- strcpy(in, argv[0]);
- strcat(in, ".in");
- freopen(in, "r", stdin);
- strcpy(out, argv[0]);
- strcat(out, ".out");
- freopen(out, "w", stdout);
- #endif
- int costs[MAX];
- char buf[20];
- int len;
- char c;
- int persons, i, j;
- int exchange;
- for (scanf("%d/n", &persons); persons != 0; scanf("%d/n", &persons)) {
- for (i = 0; i < persons; ++i) {
- for (j = 0; (c = getchar()) != '/n'; ++j) {
- if (c != '.')
- buf[j] = c;
- else
- --j;
- }
- buf[j] = '/0';
- costs[i] = atoi(buf);
- }
- exchange = calc_exchange(costs, persons);
- sprintf(buf, "%d", exchange);
- len = strlen(buf);
- if (len == 1)
- printf("$0.0%s/n", buf);
- else if (len == 2)
- printf("$0.%s/n", buf);
- else {
- putchar('$');
- for (i = 0; i < len - 2; ++i)
- putchar(buf[i]);
- printf(".%s/n", buf+len-2);
- }
- }
- return 0;
- }