HDOJ:老鼠和猫的交易/田忌赛马【贪心算法】

老鼠和猫的交易

# include <iostream>
# include <stdio.h>
# include <algorithm>

using namespace std;
struct chess {
	double total_weigh;
	double total_money;
	double per;
} C[1010];

bool cmp(chess a, chess b)
{
	if (a.per > b.per) return true;
	else return false;
}

int main(void)
{
	double my_money, cats;
	cin >> my_money >> cats;
	while (my_money != -1)
	{
		for (int i = 0; i < cats; i++)
		{
			cin >> C[i].total_weigh >> C[i].total_money;
			C[i].per = C[i].total_weigh / C[i].total_money;
		}

		sort(C, C + int(cats), cmp);

		double res = my_money;
		double buy = 0;
		for (int i = 0; i < cats && res > 0; i++)
		{
			if (res > C[i].total_money)
			{
				res -= C[i].total_money;
				buy += C[i].total_weigh;
			}
			else
			{
				buy += C[i].per * res;
				res = 0;
			}
		}
		printf("%.3lf\n", buy);
		cin >> my_money >> cats;
	}
	
	return 0;
}

田忌赛马

# include <iostream>
# include <stdio.h>
# include <algorithm>

using namespace std;

struct horse {
	int cap;
	bool used;
} king[1010], tian[1010];

bool cmp(horse a, horse b)
{
	if (a.cap > b.cap) return true;
	else return false;
}

int main(void)
{
	int n;
	cin >> n;
	while (n > 0)
	{
		for (int i = 0; i < n; i++)
			cin >> tian[i].cap;

		for (int i = 0; i < n; i++)
			cin >> king[i].cap;

		for (int i = 0; i < n; i++)
			tian[i].used = king[i].used = false;

		sort(tian, tian + n, cmp);
		sort(king, king + n, cmp);


		int win = 0, ping = 0, j = 0;
		for (int i = 0; i < n && j < n; i++)
		{
			while (j < n && tian[i].cap <= king[j].cap) j++;
			if (j < n)
			{
				tian[i].used = king[j].used = true;
				j++;
				win++;
			}
		}

		// 检查平局
		j = 0;
		for (int i = 0; i < n && j < n; i++)
		{
			if (tian[i].used) continue;
			while (j < n && !king[j].used && tian[i].cap < king[j].cap) j++;
			if (j < n &&  tian[i].cap == king[j].cap)
			{
				tian[i].used = king[j].used = true;
				j++;
				ping++;
			}
		}
		printf("%d\n", win * 200 - (n-win-ping) * 200);
		cin >> n;
	}
	
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值