Problem Description
YJJ is a salesman who has traveled through western country. YJJ is always on journey. Either is he at the destination, or on the way to destination.
One day, he is going to travel from city A to southeastern city B. Let us assume that A is (0,0) on the rectangle map and B (109,109). YJJ is so busy so he never turn back or go twice the same way, he will only move to east, south or southeast, which means, if YJJ is at (x,y) now (0≤x≤109,0≤y≤109), he will only forward to (x+1,y), (x,y+1) or (x+1,y+1).
On the rectangle map from (0,0) to (109,109), there are several villages scattering on the map. Villagers will do business deals with salesmen from northwestern, but not northern or western. In mathematical language, this means when there is a village k on (xk,yk) (1≤xk≤109,1≤yk≤109), only the one who was from (xk−1,yk−1) to (xk,yk) will be able to earn vk dollars.(YJJ may get different number of dollars from different village.)
YJJ has no time to plan the path, can you help him to find maximum of dollars YJJ can get.
Input
The first line of the input contains an integer T (1≤T≤10),which is the number of test cases.
In each case, the first line of the input contains an integer N (1≤N≤105).The following N lines, the k-th line contains 3 integers, xk,yk,vk (0≤vk≤103), which indicate that there is a village on (xk,yk) and he can get vk dollars in that village.
The positions of each village is distinct.
Output
The maximum of dollars YJJ can get.
Sample Input
1
3
1 1 1
1 2 2
3 3 1
Sample Output
3
思路:先离散化,利用线段树log查询修改,加DP
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
struct node{
int x,y,v;
}a[maxn];
int n,tr[maxn<<2];
bool cmp(node a,node b){
if(a.x!=b.x) return a.x<b.x;
return a.y>b.y;
}
int c[maxn];///离散化用
void pushup(int rt){
tr[rt]=max(tr[rt<<1],tr[rt<<1|1]);
}
void update(int a,int b,int rt,int l,int r){
if(l==r) {
tr[rt]=max(tr[rt],b);
return ;
}
if(a<=(l+r)/2) update(a,b,rt<<1,l,(l+r)/2);
else update(a,b,rt<<1|1,(l+r)/2+1,r);
pushup(rt);
}
int query(int L,int R,int rt,int l,int r){
if(L<=l&&R>=r) return tr[rt];
if(R<=(l+r)/2) return query(L,R,rt<<1,l,(l+r)/2);
else if(L>(l+r)/2) return query(L,R,rt<<1|1,(l+r)/2+1,r);
else return max(query(L,R,rt<<1,l,(l+r)/2),query(L,R,rt<<1|1,(l+r)/2+1,r));
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].v);
c[i]=a[i].y;
}
sort(c+1,c+1+n);
int m=unique(c+1,c+1+n)-(c+1);///离散化建立映射
for(int i=1;i<=n;i++) {
a[i].y=lower_bound(c+1,c+1+m,a[i].y)-c;
// printf("--%d\n",a[i].y);
}
memset(tr,0,sizeof(tr));
sort(a+1,a+n+1,cmp);
int ans=0,ma=0;
for(int i=1;i<=n;i++){
if(a[i].y==1) {
ma=0;
update(1,a[i].v,1,1,m);
}
else{
ma=query(1,a[i].y-1,1,1,m);
update(a[i].y,ma+a[i].v,1,1,m);
}
ans=max(ans,ma+a[i].v);
}
printf("%d\n",ans);
}
return 0;
}