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,但大了就不行了,转化为贪心问题。