poj 1328 经典DP 区间选择贪心

很经典的一道题,在挑战程序设计竞赛书上有,注意选择贪心策略,我选择的是对区间排序。

//============================================================================
//
// >     File        :    poj1328.cpp
// >     Author      :    flowertree
// >     Time        :    2015年11月16日
// >     Algorithm   :    贪心
//
//============================================================================

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;

#define MAX 1005

struct node
{
	double x;
	double y;
	double left;
	double right;
};

node n[MAX];

bool cmp(node xx, node yy)
{
	if(xx.left < yy.left)
		return true;
	if(xx.left == yy.left)
		return xx.right < yy.right ? true : false;
	return false;
}

double Distance(double bb, double d)
{
	double temp;
	temp = sqrt((d * d) - (bb * bb));
	return temp;
}

int dp(int m, double d)
{
	double templeft, tempright;
	templeft = n[0].left;
	tempright = n[0].right;
	int sum = 1;
	for(int i = 1; i < m; i++)
	{
		if(n[i].left > tempright)
		{
			sum++;
			templeft = n[i].left;
			tempright = n[i].right;
		}
		else
		{
			templeft = n[i].left;
			if(n[i].right < tempright)
				tempright = n[i].right;
		}
	}
	return sum;
}

int main()
{
//	freopen("in.txt", "r", stdin);
//	freopen("out.txt","w",stdout);
	int m;
	double d;
	int sum;
	int Case = 1;
	bool flag;
	double temp;
	while(cin >> m >> d, m || d)
	{
		flag = true;
		if(d <= 0)
			flag = false;
		for(int i = 0; i < m; i++)
		{
			cin >> n[i].x >> n[i].y;
			if(n[i].y > d)
				flag = false;
			temp = Distance(n[i].y, d);
			n[i].left = n[i].x - temp;
			n[i].right = n[i].x + temp;
		}
		if(!flag)
		{
			printf("Case %d: %d\n", Case++, -1);
			continue;
		}
		sort(n, n + m, cmp);
		sum = dp(m, d);
		printf("Case %d: %d\n", Case++, sum);
	}
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值