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;
}


你可能感兴趣的:(动态规划,poj)