Greedy Gift Givers
SAMPLE INPUT (file gift1.in)
5 dave laura owen vick amr dave 200 3 laura owen vick owen 500 1 dave amr 150 2 vick owen laura 0 2 amr vick vick 0 0
OUTPUT FORMAT
The output is NP lines, each with the name of a person followed by a single blank followed by the net gain or loss (final_money_value - initial_money_value) for that person. The names should be printed in the same order they appear on line 2 of the input.
All gifts are integers. Each person gives the same integer amount of money to each friend to whom any money is given, and gives as much as possible that meets this constraint. Any money not given is kept by the giver.
SAMPLE OUTPUT (file gift1.out)
dave 302 laura 66 owen -359 vick 141 amr -150
/*
ID: conicoc1
LANG: C
TASK: gift1
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Data
{
char Name[15];
int Money;
};
int Find(struct Data *People,char *Name)
{
int CurrentPos;
CurrentPos=0;
while(strcmp(People[CurrentPos].Name,Name)!=0)
{
CurrentPos++;
}
return CurrentPos;
}
int main()
{
FILE *fin,*fout;
fin=fopen("gift1.in","r");
fout=fopen("gift1.out","w");
int i,j;
char Name[15];
int PeopleNumber;
int Rest;
int InitialMoney,GiveNumber;
int GiveMoney;
fscanf(fin,"%d",&PeopleNumber);
struct Data *People=(struct Data *)malloc(sizeof(struct Data)*PeopleNumber);
for(i=0;i<PeopleNumber;i++) //初始化
{
fscanf(fin,"%s",People[i].Name);
// printf("%s\n",People[i].Name);
People[i].Money=0;
}
for(i=0;i<PeopleNumber;i++)
{
fscanf(fin,"%s",Name);
fscanf(fin,"%d",&InitialMoney);
fscanf(fin,"%d",&GiveNumber);
// printf("%s\n%d,%d\n",Name,InitialMoney,GiveNumber);
if(GiveNumber!=0)
{
GiveMoney=InitialMoney/GiveNumber;
Rest=InitialMoney%GiveNumber;
}
else
{
GiveMoney=0;
Rest=0;
}
// printf("%d",GiveMoney);
People[Find(People,Name)].Money-=(InitialMoney-Rest);
for(j=0;j<GiveNumber;j++)
{
fscanf(fin,"%s",Name);
People[Find(People,Name)].Money+=GiveMoney;
}
}
for(i=0;i<PeopleNumber;i++)
{
fprintf(fout,"%s %d\n",People[i].Name,People[i].Money);
}
return 0;
}
有N个人分钱,需要根据名字以O(N)复杂度查找下标,可以用哈希表进行优化
分钱时,注意被除数等于0的情况,以及余数,用于分的钱中不计入已经被分到的钱。