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 SS and use a 'budget 'to record the extra cents that shocould 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>
- # Deprecision 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;
- }