版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/C_13579/article/details/82078743
地址:http://acm.hdu.edu.cn/showproblem.php?pid=6447
思路:DP+线段树+离散化,题目要得到价值必须是由左上到右下才行,用dp的话对于 dp[i][j]=max{dp[t1][t2]}+a[i][j] (1<=t1<i,1<=t2<j),这样的话就需要四重循环,肯定超时,但是可以先将所有点按照x由小到大排序,这样就只需要考虑 1<=t2<j的点的最大值了,而y轴的前j的最大值可以用线段树来维护就可以了,y<=1^9因此需要对其离散化。
Code :
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<map>
using namespace std;
struct node{
int x;
int y;
int w;
bool operator<(const node &p)const{
if(x==p.x){
return y>p.y;
}else return x<p.x;
}
};
const int MAX_N=100005;
int n,T;
node a[MAX_N];
int d[MAX_N];
int tree[MAX_N*4];
void PushUp(int id); //求区间最大值
void Build(int l,int r,int id);
void Update(int t,int x,int L,int R,int id);
int Query(int l,int r,int L,int R,int id);
int main()
{
scanf("%d",&T);
while(T--){
scanf("%d",&n);
int x,y,w;
map<int,int> imap;
for(int i=0;i<n;++i)
{
scanf("%d%d%d",&x,&y,&w);
a[i].x=x; a[i].y=y; a[i].w=w;
imap[y]=1; d[i]=0;
}
d[n]=0;
sort(a,a+n);
int m=0;
for(auto c:imap)
imap[c.first]=++m;
Build(1,m,1);
int ans=0,Max;
for(int i=0;i<n;++i)
{
y=imap[a[i].y];
if(y==1) Max=0;
else Max=Query(1,y-1,1,m,1);
d[y]=max(d[y],Max+a[i].w);
Update(y,d[y],1,m,1);
ans=max(ans,d[y]);
}
printf("%d\n",ans);
}
return 0;
}
void PushUp(int id)
{
tree[id]=max(tree[id<<1],tree[id<<1|1]);
}
void Build(int l,int r,int id)
{
if(l==r){
tree[id]=0;
return;
}
int h=(l+r)>>1;
Build(l,h,id<<1);
Build(h+1,r,id<<1|1);
PushUp(id);
}
void Update(int t,int x,int l,int r,int id)
{
if(l==r){
tree[id]=x;
return;
}
int h=(l+r)>>1;
if(t<=h){
Update(t,x,l,h,id<<1);
}else Update(t,x,h+1,r,id<<1|1);
PushUp(id);
}
int Query(int l,int r,int L,int R,int id)
{
if(l<=L&&r>=R){
return tree[id];
}
int h=(L+R)>>1;
int s1=0,s2=0;
if(h>=l) s1=Query(l,r,L,h,id<<1);
if(h+1<=r) s2=Query(l,r,h+1,R,id<<1|1);
return max(s1,s2);
}