USACO Greedy Gift Givers

1、第一次用map和string类。。。还是很方便的。

/*
ID:mrxy564
PROG:gift1
LANG:C++
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
int cnt;
map<string,int> id;
int ID(string s){
   if(!id.count(s)) id[s]=cnt++;
   return id[s];
}
int main()
{
    freopen("gift1.in","r",stdin);
    freopen("gift1.out","w",stdout);
    string s;
    string np[15];
    int n,num;
    int premoney[15],money[15];
    cnt=0;
    memset(money,0,sizeof(money));
    scanf("%d",&n);
    for(int i=0;i<n;i++){
       cin>>s;
       np[i]=s;
       ID(s);
    }
    for(int i=0;i<n;i++){
      cin>>s;
      scanf("%d%d",&premoney[ID(s)],&num);
      int temp;
      if(num) temp=premoney[ID(s)]/num;
      else temp=0;
      money[ID(s)]+=premoney[ID(s)]-temp*num;
      for(int i=0;i<num;i++){
        cin>>s;
        money[ID(s)]+=temp;
    }
    }
    for(int i=0;i<n;i++)
       cout<<np[i]<<" "<<money[ID(np[i])]-premoney[ID(np[i])]<<endl;
    return 0;
}
官方题解:

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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值