我的:
问题的难点是:题目的理解和名字的存储。
get[]存放的是得到的钱,money[]开始是送礼者原来钱数,然后存储送出的总钱数
这个题用文件在Code blocks上通不过但提交时就OK了,不知咋回事
/*
ID:90girl1
PROG: gift1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<string>
#define NP 15
using namespace std;
int main()
{
ifstream fin("gift1.in");
ofstream fout("gift1.out");
int np,get[NP],money[NP],n,i,j,k,l;//get[]为得到的钱,money[]为财富,最后为支出钱数
string name[NP],giver,geter;
fin>>np;//数据个数
for(i=0; i<np; i++)
{
fin>>name[i];
get[i]=0;
money[i]=0;
}
for(j=0; j<np; j++)
{
fin>>giver;
for(k=0; k<np; k++)
if(name[k]==giver)
break;
//每个人的钱数和分钱人数初始化
fin>>money[k]>>n; //此处的k即为上面if判断条件的k;
for(l=0; l<n; l++)
{
fin>>geter;
for(i=0; i<np; i++)
if(name[i]==geter)
break;
get[i]+=money[k]/n; //sb丢了个+~~~~(>_<)~~~~
}
if(n)
money[k]=(money[k]/n)*n;
}
for(i=0;i<np;i++)
fout<<name[i]<<" "<<get[i]-money[i]<<endl;
return 0;
}
UASCO题解:
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);
}
本文探讨使用C++编程解决礼物交换问题,通过输入数据和处理字符串来计算每个人送出和收到的钱数,并将结果输出到文件。文章涉及字符串操作、数组应用及文件流的使用。
1071

被折叠的 条评论
为什么被折叠?



