现在的位置: 首页 > 综合 > 正文

HDU 1160 FatMouse’s Speed dp

2012年04月18日 ⁄ 综合 ⁄ 共 1257字 ⁄ 字号 评论关闭

        这题是看杭电acm课件做的,和一维的最长有序子序列差不多。

        先按mice的重量为第一关键字升序排序,再按mice的speed按降序排序,然后开始dp

        对杭电课件那个记录数组的意义不理解。

        num[i]是记录从0~i个mice的最长子序列,num[i] = max (num[j]+1, num[i]) , 0<= j < i

        一开始用string保存路径输出,不断地WA,想了很久,才发现问题,我每次用一个char保存当前的节点,char是值是0~2^8,会越界

       后来查考别人输出方法,每个节点保存一个前节点,最后一个递归输出即可。

       对memset又加深了理解,memset不能对int数组赋值,例如不能给整个数组赋值为1, 它是按位赋值的,一个int是4个位,它会把所有位都赋值为1,得到的就不是1了。

#include <iostream>
#include <algorithm>
#define MAX 1005
using namespace std;

struct Mice
{
	int id;
	int weight;
	int speed;
	int pre;
};


bool cmp(const Mice& a, const Mice& b)
{
	if (a.weight < b.weight)
		return true;
	else if (a.weight == b.weight)
		return a.speed > b.speed;
	else
		return false;
}

int num[MAX];
Mice mice[MAX];

void output(int);

int main()
{
	int count = 0;

	while (cin >> mice[count].weight >> mice[count].speed)
	{
		mice[count].id = count+1;
		count++;
	}

	
	sort(mice, mice+count, cmp);

 	num[0] = 1;
	mice[0].pre = 0;

	for (int i = 1; i < count; i++)
	{
		num[i] = 1;
		mice[i].pre = i;

		for (int j = 0; j < i; j++)
		{
			if (mice[i].weight > mice[j].weight && mice[i].speed < mice[j].speed)
			{
				if (num[i] < num[j]+1)
				{
					num[i] = num[j]+1;
					mice[i].pre = j;
				}
			}
		}

	}

	int max_index = 0;
	for (int i = 1; i < count; i++)
		if (num[i] > num[max_index])
			max_index = i;
			
	cout << num[max_index] << endl;

	output(max_index);
	return 0;
}


void output(int index)
{
	if (num[index] == 1)
		cout << mice[index].id << endl;
	else
	{
		output(mice[index].pre);
		cout << mice[index].id << endl;
	}
}

抱歉!评论已关闭.