C++喷水装置 贪心

题目 (vector+pair写法)

结构体数组

#include<iostream>
#include<algorithm>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<vector>
#include<stack>
using namespace std;

/*
3
8 20 2
5 3
4 1
1 2
7 2
10 2
13 3
16 2
19 4
3 10 1
3 5
9 3
6 1
3 10 1
5 3
1 1
9 1
*/

struct Data
{
	double a;
	double b;
}sh[99999];

bool cmp(Data d1, Data d2)//比较器
{
	return d1.a < d2.a;
}
int main()
{
	int i;
	int T;
	cin >> T;

	int n;
	double L;
	double W;

	while (T--)
	{

		cin >> n >> L >> W;

		i = 0;

		for (int j = 0; j < n; j++)
		{
			double x;
			double r;
			cin >> x >> r;
			if (r < W / 2)
				continue;

			double d = sqrt(r * r - (W / 2) * (W / 2));  	//用a保存左端点,用b保存右端点 
			sh[i].a = x - d;
			sh[i].b = x + d;
			i++;

		}
		n = i; //去掉半径小于W/2后的剩余装置
	
		sort(sh, sh + n, cmp); //左端点递增排序

		double Long=0;//右端已经喷水的距离
		int flag = 1;
		i = 0;
		int c = 0;
		while (i < n)
		{
			if (sh[i].a > Long) //有部分无法完全覆盖
			{
				flag = 0;
				break;
			}
			if (Long >= L) //已经完全覆盖,停止计数
			{
				break;
			}
			double max = -1;
			while (i < n && sh[i].a <= Long) //在左端点不超过当前已覆盖的范围,选取右端点最大的 
			{
				max = max > sh[i].b ? max : sh[i].b;
				i++;
			}
			Long = max;
			c++;
		}
	
		if (flag == 0 && Long < L)
			cout << "-1" << endl;
		else
			cout << c << endl;
	
	
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
背包问题是一个经典的动态规划问题,但是也可以使用贪心算法来解决。以下是使用贪心算法解决 0/1 背包问题的步骤: 1. 计算每个物品的单位价值,即价值与重量的比值。 2. 按照单位价值从大到小的顺序对物品进行排序。 3. 从价值最高的物品开始,依次放入背包中,直到放不下为止。 代码实现如下: ```c++ #include <iostream> #include <algorithm> using namespace std; struct Item { int weight; int value; double unitValue; }; bool cmp(Item a, Item b) { return a.unitValue > b.unitValue; } int knapsack(Item items[], int n, int capacity) { sort(items, items + n, cmp); //按单位价值从大到小排序 int curWeight = 0; double curValue = 0.0; for (int i = 0; i < n; i++) { if (curWeight + items[i].weight <= capacity) { curWeight += items[i].weight; curValue += items[i].value; } else { int remainWeight = capacity - curWeight; curValue += items[i].unitValue * remainWeight; break; } } return curValue; } int main() { Item items[] = {{10, 60}, {20, 100}, {30, 120}}; int n = sizeof(items) / sizeof(items[0]); int capacity = 50; for (int i = 0; i < n; i++) { items[i].unitValue = items[i].value * 1.0 / items[i].weight; } cout << "Max value: " << knapsack(items, n, capacity) << endl; return 0; } ``` 以上代码中,Item 结构体表示一个物品,其中 weight 表示重量,value 表示价值,unitValue 表示单位价值。在 knapsack 函数中,首先按照单位价值从大到小排序,然后依次将物品放入背包中,直到放不下为止。如果当前物品无法完全放入背包中,那么就只放入能够放下的部分,然后结束循环。最后返回当前背包的总价值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值