Greedy Gift Givers(USACO)

/* ID:tianlin2 PROG:gift1 LANG:C++ */ #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ofstream fout("gift1.out"); ifstream fin("gift1.in"); int mo,ge; int a,b=0,c=0; string s1,s2; fin>>a; string *st=new string[a]; int *mon=new int[a]; for(int i=0;i!=a;++i) fin>>st[i]; for(int i=0;i!=a;++i) mon[i]=0; for(int i=0;i!=a;++i) { fin>>s1; fin>>mo>>ge; for(int j=0;j!=a;++j) { if(st[j]==s1) mon[j]-=mo; } for(int j=0;j!=ge;++j) { fin>>s2; for(int x=0;x!=a;++x) { if(st[x]==s2) { mon[x]+=mo/ge; if(ge!=0) mon[x]+=mo%ge; //余下的钱归自己所有 } } } } for(int i=0;i!=a;++i) fout<<st[i]<<' '<<mon[i]<<endl; delete [] st; delete [] mon; fout.close(); fin.close(); system("pause"); return 0; }

这里主要运用了两个数组!一个保存名字,一个保存钱的数目!名字保存的位置对应着另一个数组的钱的位置!即st[0]对应mon[0];

要注意如果钱不能整除个数的话,余下的钱的话就归自己所有了!

#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++) printf("%s %d/n", people[i].name, people[i].total); exit (0); }

(官方答案)这里运用到STRUCT,比数组的方便多了!

 

你可能感兴趣的:(Greedy Gift Givers(USACO))