K - Jack‘s struggle(动态规划+最长子数列)

A team of airborne troops are ready to complete some missions.
The battlefield was divided into a grid of n*n, this team can be air-dropped at any place on time 0. In every time unit after landing, they can go to the grid left, right, up or down to the current grid, or they can just stay.
On their mission list, each mission is described as three integers: t, r and c, represents a task that must be completed exactly at time t on the grid (r, c).
Obviously, with limits of time, not all missions can be done.
The captain, Jack, struggling making decisions, wants to know how many missions they can complete at most.
Input
The input contains serveral cases:

For each case:

  • The first line contains two integers n and m, 1<=n<=1000, 1<=m<=10000, n represents the size of the battlefield and m represents the number of missions on the list.

  • Following m lines, each one describes a mission using three integers, t, r and c.

No two missions have the same t, r and c.

The input is terminated by n=m=0.
Output
One integer in one line represents the maximum number of mission that can be completed.
Sample Input
2 2
1 1 1
2 2 2
0 0
Sample Output
1

#include<iostream>
#include <math.h>
#include <algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
int const N=10006;
int  dp[N];
struct hh{
	int t;
	int r;
	int c;
}a[N];
bool cmp(hh x,hh y){//按时间从小到大排序
	return x.t<y.t;
}
int main()
{
    int n,m;
    while(cin>>n>>m&&n&&m)
    {
    for(int i=1;i<=m;i++)
    cin>>a[i].t>>a[i].r>>a[i].c;
    sort(a+1,a+m+1,cmp);
    int maxn=-1;
    memset(dp,0,sizeof(dp));//多组输入,记得dp随时清0
    for(int i=1;i<=m;i++)
    {
    	dp[i]=1;
    	for(int j=1;j<i;j++)
    	{
    		int len;
    		len=abs(a[i].r-a[j].r)+abs(a[i].c-a[j].c);//a[i]点到a[j]的距离,即要花费的时间点
    		if(len<=abs(a[i].t-a[j].t))
    			dp[i]=max(dp[i],dp[j]+1);
		}
			if(dp[i]>maxn)
			maxn=dp[i];
	}
	cout<<maxn<<endl;
	}
    return 0;
}

题解:
本题是要寻找最多的任务个数,可以发现这是一道寻找最长子数列的问题,
用数组dp[i],表示储存的任务个数,例如,dp[3]表示从第一个位置到底3个位置所完成的任务个数,动态规划思想然后就是,让第3个和之前的前几位进行比较,前面的哪一位满足条件,就把当位的dp[j]+1,最后不断找最大即可,
最长子数列问题在数据小时可以用dp,但大了就不行了,转化为贪心问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值