题目地址
- 刚开始由题意的输出中最后一个输入是零,导致错误的理解了跳出循环的条件是num==0,还是没有正确理解题意,以后要多做这些题,哎,。。。。 不说了,以后加油!!!
以下是本人AC代码:
/*
ID:Bean
LANG:C
PROG:gift1
*/
#include <stdio.h>
#include <string.h>
struct people {
char name[15];
int money_in;
int money_out;
int all;
}people[10];
int main()
{
freopen("gift1.in","r",stdin);
freopen("gift1.out","w",stdout);
int n, i, j;
scanf("%d", &n);
for(i = 0;i < n;i ++)
{
scanf("%s", people[i].name);
people[i].money_in = people[i].money_out = people[i].all =0;
}
char tmp[15];
int num, money;
int count = n;
while(count --)
{
scanf("%s", tmp);
for(i = 0;strcmp(tmp,people[i].name);i++);
scanf("%d %d", &people[i].all, &num);
int cnt = i;
for(i = 0;i < num;i ++)
{
scanf("%s", tmp);
for(j = 0;strcmp(tmp,people[j].name);j++);
{people[j].money_in += people[cnt].all / num;
people[cnt].money_out += people[cnt].all / num;}
}
}
for(i = 0;i < n;i ++)
printf("%s %d\n", people[i].name, - (people[i].money_out - people[i].money_in));
return 0;
}
以下是usaco提供代码:
The hardest part about this problem is dealing with the strings representing people's names.
We keep an array of Person structures that contain their name and how much money they give/get.
The heart of the program is the lookup() function that, given a person's name, returns their Person structure. We add new people with addperson().
Note that we assume names are reasonably short.
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define MAXPEOPLE 10
#define NAMELEN 32
typedef struct Person Person;
struct Person {
char name[NAMELEN];
int total;
};
Person people[MAXPEOPLE];
int npeople;
void
addperson(char *name)
{
assert(npeople < MAXPEOPLE);
strcpy(people[npeople].name, name);
npeople++;
}
Person*
lookup(char *name)
{
int i;
/* look for name in people table */
for(i=0; i<npeople; i++)
if(strcmp(name, people[i].name) == 0)
return &people[i];
assert(0); /* should have found name */
}
int
main(void)
{
char name[NAMELEN];
FILE *fin, *fout;
int i, j, np, amt, ng;
Person *giver, *receiver;
fin = fopen("gift1.in", "r");
fout = fopen("gift1.out", "w");
fscanf(fin, "%d", &np);
assert(np <= MAXPEOPLE);
for(i=0; i<np; i++) {
fscanf(fin, "%s", name);
addperson(name);
}
/* process gift lines */
for(i=0; i<np; i++) {
fscanf(fin, "%s %d %d", name, &amt, &ng);
giver = lookup(name);
for(j=0; j<ng; j++) {
fscanf(fin, "%s", name);
receiver = lookup(name);
giver->total -= amt/ng;
receiver->total += amt/ng;
}
}
/* print gift totals */
for(i=0; i<np; i++)
fprintf(fout, "%s %d\n", people[i].name, people[i].total);
exit (0);
}