题意:
样例: 1 5 1 1 2 3 3 2 4 3 5 1第一行代表有几组数据,接下来代表有几颗苹果,然后接下来每一行是苹果的高度和甜度,问这个人和他女朋友最多能吃到多少个苹果,每个人吃的甜度要一个比一个甜。
因为一个苹果可以选择不吃,所以可以不用考虑高度的问题,直接挨着摘苹果,仅考虑甜度问题,而且两个人分开吃,所以dp有两个变量。
dp[i][j] 表示上一次男女吃的甜度分别为i, j的时候的吃的最多的苹果。
那么dp[i][j] = max(dp[i][k] + 1), 0 < k <= j
dp[i][j] = max( max(dp[k][j]) + 1 ) , 0 < k <= i
对于第一个式子最大值 用树状数组线段树都可以解决, 第二个式子如果每次从0遍历到i再找最值的话,显然会超时。
仔细想想便可以发现第二个最值和第一个是一样的。 这个不好解释。 像是对称性那种 一样。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1001;
struct Node{
int h, d;
bool operator < (const Node &rhs)const{
return h != rhs.h ? h > rhs.h : d < rhs.d;
}
}apple[MAXN];
int arr[MAXN<<1][MAXN<<1];
int MAX;
inline int lowbit (int x){
return x & -x;
}
void Modify (int x, int y, int d){
while (y < MAX){
arr[x][y] = max(arr[x][y], d);
y += lowbit(y);
}
}
int query (int x, int y){
int res = 0;
while (y){
res = max(arr[x][y], res);
y -= lowbit(y);
}
return res;
}
int lsh[MAXN << 1], lshtot, tmp[MAXN << 1];
int main()
{
int T, n;
scanf ("%d", &T);
while (T--){
scanf ("%d", &n);
lshtot = 0;
for (int i = 0; i < n; i++){
scanf ("%d%d", &apple[i].h, &apple[i].d);
lsh[lshtot++] = apple[i].d;
}
sort (apple, apple+n);
sort (lsh, lsh+lshtot);
lshtot = unique(lsh, lsh+lshtot) - lsh;
for (int i = 0; i < n; i++){
apple[i].d = lower_bound(lsh, lsh+lshtot, apple[i].d) - lsh + 2;
}
MAX = lshtot + 5;
memset(arr, 0, sizeof (arr));
for (int i = 0; i < n; i++){
for (int j = 2; j <= lshtot+1; j++){
tmp[j] = query(j, apple[i].d);
}
for (int j = 2; j <= lshtot+1; j++){
Modify(apple[i].d, j, tmp[j]+1);
Modify(j, apple[i].d, tmp[j]+1);
}
}
int ans = 0;
for (int i = 1; i <= lshtot+1; i++){
ans = max(ans, query(i, lshtot+1));
}
printf("%d\n", ans);
}
return 0;
}