题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6447
YJJ's SalesmanTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2062 Accepted Submission(s): 776 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.
Input The first line of the input contains an integer T (1≤T≤10) ,which is the number of test cases.
Output The maximum of dollars YJJ can get.
Sample Input 1 3 1 1 1 1 2 2 3 3 1
Sample Output 3 |
题目大意:从(0,0)走到(1e9,1e9),假设此刻在(xk,yk),那么只能走到(xk+1,yk),(xk,yk+1),(xk+1,yk+1),且走到(xk+1,yk+1)时能获得(xk,yk)的值vk,求到达终点时的最大值
思路:这题本身思路不难,简单的dp问题,状态转移方程为dp[x][y] = max(dp[x-1][y],dp[x][y-1],dp[x-1][y-1]+v[x-1][y-1])。但关键是,这题数据量很大,直接建图dp连内存都不够。所幸题目vk>0的点最多只有1e5,所以需要用到离散化。离散化后,每给点都需要向前查找最大值,所以O(n^2),利用树状数组可以减到O(nlogn)。
附上AC代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
struct node
{
int x,y,value;
}mp[100005];
int sum[100005],a[100005],t,n;
bool cmp(node a ,node b)
{
if(a.x != b.x)
return a.x < b.x;
return a.y > b.y;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int p,int val)
{
for(int i = p;i <= n;i+=lowbit(i))
sum[i] = max(sum[i],val);
}
int query(int p)
{
int ans = 0;
for(int i = p;i >= 1;i-=lowbit(i))
ans = max(sum[i],ans);
return ans;
}
int main()
{
while(scanf("%d",&t) !=EOF)
{
while(t--)
{
memset(sum,0,sizeof(sum));
scanf("%d",&n);
for(int i = 1;i <= n;i++)
{
scanf("%d%d%d",&mp[i].x,&mp[i].y,&mp[i].value);
a[i] = mp[i].y;//a[i]将y离散化
}
sort(a+1,a+1+n);
int all = unique(a+1,a+1+n)-a-1;//去重
sort(mp+1,mp+1+n,cmp);
for(int i = 1;i <= n;i++)
{
int Y = lower_bound(a+1,a+1+all,mp[i].y)-a;//查找当前y的大小对应的位置
int val = query(Y-1)+mp[i].value;
update(Y,val);
}
cout << query(n) << endl;
}
}
//cout << "AC" << endl;
return 0;
}