赵乐ACM

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 贪心,其他没啥说的

2. 我的代码:

/*
ID: dollar4
PROG: milk
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>

using namespace std;
struct Node
{
    int price;
    int num;
} node[5000];
bool cmp(Node a, Node b)
{
    return a.price < b.price;
}
int main()
{
    ofstream fout ("milk.out");
    ifstream fin ("milk.in");
    int n, m, i;
    fin >> n >> m;
    for (i = 0; i < m; i++)
        fin >> node[i].price >> node[i].num;
    sort(node, node + m, cmp);
    int money = 0, sum = 0, j = 0;
    while (sum < n)
    {
        sum += node[j].num;
        money += node[j].num * node[j].price;
        j++;
    }
    int rst = money - (sum - n) * node[j-1].price;
    fout << rst << endl;
    return 0;
}

3. 官方参考代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define MAXFARMER 5000

typedef struct Farmer Farmer;
struct Farmer {
	int p;	/* price per gallon */
	int a;	/* amount to sell */
};

int
farmcmp(const void *va, const void *vb)
{
	return ((Farmer*)va)->p - ((Farmer*)vb)->p;
}

int nfarmer;
Farmer farmer[MAXFARMER];

void
main(void)
{
	FILE *fin, *fout;
	int i, n, a, p;

	fin = fopen("milk.in", "r");
	fout = fopen("milk.out", "w");

	assert(fin != NULL && fout != NULL);

	fscanf(fin, "%d %d", &n, &nfarmer);
	for(i=0; i<nfarmer; i++)
		fscanf(fin, "%d %d", &farmer[i].p, &farmer[i].a);

	qsort(farmer, nfarmer, sizeof(farmer[0]), farmcmp);

	p = 0;
	for(i=0; i<nfarmer && n > 0; i++) {
		/* take as much as possible from farmer[i], up to amount n */
		a = farmer[i].a;
		if(a > n)
			a = n;
		p += a*farmer[i].p;
		n -= a;
	}

	fprintf(fout, "%d\n", p);
	exit(0);
}


posted on 2012-04-11 10:25  赵乐ACM  阅读(150)  评论(0编辑  收藏  举报