贪心类问题

此类问题运用贪心算法,首先要找出按照哪一变量进行贪心化,利用sort函数进行排序

例1 九度1433 FatMouse's Trade

该题的贪心化点为性价比高的物品优先

题目描述:

FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain. 

输入:

The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.

输出:

For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.

样例输入:
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
样例输出:
13.333
31.500
#include
#include
using namespace std;
#include

//定义物品结构体 
struct G{
	double j; //该物品的重量
	double f; //该物品的价值
	double s; //该物品的性价比
}goods[1000];
bool cmp(G g1,G g2)
{
	return g1.s>g2.s;
}
int main(int argc, char* argv[])
{
	int N;  
	double M;//M为总钱数,注意为double类型
	while(scanf("%lf %d",&M,&N)!=EOF)
	{
		if(M==-1&&N==-1)	break;
		int i;
		for(i=0;i0&&igoods[i].f)
			{
				M-=goods[i].f;
				max+=goods[i].j;
			}
			else{
				max+=(M/goods[i].f)*goods[i].j;
				M=0;
			}
			i++;
		}
		printf("%.3lf\n",max);
	}
	return 0;
}

例2 九度1434

该题的贪心化点为结束时间较短的电视节目优先

题目描述:

“今年暑假不AC?”“是的。”“那你干什么呢?”“看世界杯呀,笨蛋!”“@#$%^&*%...”确实如此,世界杯来了,球迷的节日也来了,估计很多ACMer也会抛开电脑,奔向电视作为球迷,一定想看尽量多的完整的比赛,当然,作为新时代的好青年,你一定还会看一些其它的节目,比如新闻联播(永远不要忘记关心国家大事)、非常6+7、超级女生,以及王小丫的《开心辞典》等等,假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)

输入:

输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据Ti_s,Ti_e (1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不做处理。

输出:

对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。

样例输入:
12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0
样例输出:
5
#include
#include
#include
using namespace std;

//定义电视节目结构体
struct P{
	int st;
	int et;
}program[100];
bool cmp(P p1,P p2)
{
	return p1.et


你可能感兴趣的:(贪心类问题)