0
点赞
收藏
分享

微信扫一扫

HDOJ1176免费馅饼--动态规划探骊(一)


Problem Description

都说天上不会掉馅饼,但有一天gameboy正走在回家的小径上,忽然天上掉下大把大把的馅饼。说来gameboy的人品实在是太好了,这馅饼别处都不掉,就掉落在他身旁的10米范围内。馅饼如果掉在了地上当然就不能吃了,所以gameboy马上卸下身上的背包去接。但由于小径两侧都不能站人,所以他只能在小径上接。由于gameboy平时老呆在房间里玩游戏,虽然在游戏中是个身手敏捷的高手,但在现实中运动神经特别迟钝,每秒种只有在移动不超过一米的范围内接住坠落的馅饼。现在给这条小径如图标上坐标:

HDOJ1176免费馅饼--动态规划探骊(一)_初始化

为了使问题简化,假设在接下来的一段时间里,馅饼都掉落在0-10这11个位置。开始时gameboy站在5这个位置,因此在第一秒,他只能接到4,5,6这三个位置中其中一个位置上的馅饼。问gameboy最多可能接到多少个馅饼?(假设他的背包可以容纳无穷多个馅饼)

 


Input

输入数据有多组。每组数据的第一行为以正整数n(0<n<100000),表示有n个馅饼掉在这条小径上。在结下来的n行中,每行有两个整数x,T(0<T<100000),表示在第T秒有一个馅饼掉在x点上。同一秒钟在同一点上可能掉下多个馅饼。n=0时输入结束。

 


Output

每一组输入数据对应一行输出。输出一个整数m,表示gameboy最多可能接到m个馅饼。
提示:本题的输入数据量比较大,建议用scanf读入,用cin可能会超时。

 


Sample Input

6 5 1 4 1 6 1 7 2 7 2 8 3 0

 


Sample Output

4

本题思路:

典型的动态规划问题,第i时刻1~9位置收到的最多大饼数量为

a[i][loc]=max(a[i+1][loc-1],a[i+1][loc],a[i+1][loc+1])+a[i][loc];

第i时刻0位置收到的最多大饼数量为

a[i][loc]=max(a[i+1][loc],a[i+1][loc+1])+a[i][loc](10位置类似)

location time

5(0) 0

/ | \

4(1) 5(1) 6(1) 1

|

7(2) 2

|

8(1) 3

最开始将a[][]初始化为0,最后a[0][5]即是最终结果。

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int num_location[100005][11];//num_location[0][5]代表从第0时刻5号位置开始gameboy获得的最多大饼子
int n;
int max_2(int a, int b)
{
if (a > b) { return a; }
else { return b; }
}
int max_3(int a, int b, int c)
{
int max;
max = (a > b ? a : b);
if (max > c) { return max; }
else { return c; }
}
int main()
{
int location, time;
while(cin >> n && n != 0)
{
int max_time = 0;
memset(num_location, 0, sizeof(num_location));//初始化矩阵,所有时刻所有地点都没有大饼子
while (n--)//输入所有时刻-地点关系,计算时间最大值
{
scanf("%d %d", &location, &time);
num_location[time][location] ++;//计算第time时刻location位置空降大饼的数目
if (time > max_time) { max_time = time; }
}
//cout << "max_time是多少?" << max_time << endl;
for (int i = max_time - 1; i >= 0; i--)
{
//0 and 10 这两个端点位置
num_location[i][0] = max_2(num_location[i + 1][0], num_location[i + 1][1]) + num_location[i][0];
num_location[i][10] = max_2(num_location[i + 1][9], num_location[i + 1][10]) + num_location[i][10];
//1~9这九个点每个点的周围三个点都进行计算
for (int j = 1; j < 10; j++)
{
num_location[i][j] = max_3(num_location[i + 1][j - 1], num_location[i + 1][j], num_location[i + 1][j + 1]) + num_location[i][j];
}
}
cout << num_location[0][5] << endl;
}
return 0;
}


举报

相关推荐

0 条评论