【“盛大游戏杯”第15届上海大学程序设计联赛 K】【贪心】购买装备

购买装备

发布时间: 2017年7月9日 18:17   最后更新: 2017年7月9日 21:05   时间限制: 1000ms   内存限制: 128M

最近盛大的一款游戏传奇世界极其火爆。游戏玩家John,想购买游戏中的装备。已知游戏的商店里有n件装备,第i件装备具有属性值ai,购买需要花费bi个金币。John想去购买这些装备,但是账号中只有m个金币,John是个很贪婪的家伙,他想购买尽可能多的装备。并且在保证购买到最多件装备的情况下,他还想让他所购买的装备当中拥有最小属性值的装备属性值尽可能大

输入测试组数T,每组数据第一行输入整数n(1<=n<=100000)和m(1<=m<=109), 接下来有n行,第i行有两个数aibi(1<=ai,bi<=10000).

对于每组数据,输出两个数字,第一个数字代表John最多可以购买的装备数,第二个数代表在John购买最多件装备的前提下,所购买的装备当中拥有最小属性值的装备的最大属性值(输入数据保证至少可以购买一件装备)

1
2 4
3 2
2 3
1 3

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
#define MS(x, y) memset(x, y, sizeof(x))
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b > a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b < a)a = b; }
const int N = 1e5 + 10, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f;
template <class T1, class T2>inline void gadd(T1 &a, T2 b) { a = (a + b) % Z; }
int casenum, casei;
int n, m;
struct A
{
	int v, c;
	bool operator < (const A & b)const
	{
		return c < b.c;
	}
}a[N];
struct Node
{
	int v, c;
	bool operator < (const Node & b)const
	{
		if (v != b.v)return v > b.v;
		return c > b.c;
	}
};
int sum[N];
priority_queue<Node>q;

int main()
{
	scanf("%d", &casenum);
	for (casei = 1; casei <= casenum; ++casei)
	{
		scanf("%d%d", &n, &m);
		for (int i = 1; i <= n; ++i)
		{
			scanf("%d%d", &a[i].v, &a[i].c);
		}
		//先按照价格从小到大排序,得出数量
		sort(a + 1, a + n + 1);
		while (!q.empty())q.pop();

		//首先求得了最多能买的物品数量
		int num = 0;
		int nowCost = 0;
		for (int i = 1; i <= n; ++i)
		{
			sum[i] = sum[i - 1] + a[i].c;
			if (sum[i] <= m)
			{
				num = i;
				nowCost = sum[i];
				q.push({ a[i].v,a[i].c });
			}
		}

		//一开始把所有合法的都扔进去,然后开始考虑替换
		if (q.empty())
		{
			puts("0 0");
			continue;
		}
		for (int i = num + 1; i <= n; ++i)
		{
			Node it = q.top();
			if (a[i].v > it.v && nowCost - it.c + a[i].c <= m)
			{
				nowCost -= it.c;
				nowCost += a[i].c;
				q.pop();
				q.push({ a[i].v,a[i].c });
			}
		}
		printf("%d %d\n", num, q.top().v);
	}
	return 0;
}
/*
【题意】
http://acmoj.shu.edu.cn/problem/420/

【分析】
首先,一定要先求出最多能购买的数量
然后可以用优先队列逐渐把当前价值低的替换掉,替换到不能替换为止(这个可以剪枝)
也可以二分,这个比较好写。

【时间复杂度&&优化】
O(nlogn)

*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章