跳到正文

题解

题解 P3431 【[POI2005]AUT-The Bus】

Tethys约 4 分钟
原文
文章信息与版本

文章信息

发布
2020年10月6日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 4 分钟
获赞
7
题目
P3431

版本

  1. v1当前

题意:

给定网格图上的点,求一条最大的权值的不下降的路径,输出一下最大权值

思路:

假设我们当前在点(x,y)(x, y),我们能够知道,求得当前点的最优解的话,需要找一个max⁡fi,j(i≤x\max f_{i,j}(i\leq x且j≤y)j \leq y)(ff为之前求的最优解),然后用那个答案来更新, 所以我们可以想到树状数组

树状数组求最大值

C++
	inline int lowbit(int x){ return x & (-x);}
	void change(int x, long long val){
		while(x < N){
			tr[x] = std::max(tr[x], val);
			x += lowbit(x);
		}
	}
	inline long long query(int x){
		long long res = 0;
		for(res = std::max(res, tr[x]); (x -= lowbit(x)); res = std::max(res, tr[x]));
		return res;
	}

我们先按横坐标排序,使得这个点之前的点一定在它的左边(西边),然后在纵坐标上进行树状数组的操作就好了,我们在每次求点的最优解的时候直接更新答案就好了,因为可以从这个点不走剩下的点到达终点

然后求完当前点的最优解之后,更新一下当前纵坐标及以上的最优解

注:记得把纵坐标离散化,不然会很惨的(因为范围是≤1e9\leq 1e9),我一般用lower_boundlower\_bound来进行离散化

代码:

C++
#include<bits/stdc++.h>
const int N = 1e6 + 5;

namespace Tethys{
	inline long long read(){
		long long s = 0, f = 1; char ch;
		while(!isdigit(ch = getchar())) (ch == '-') && (f = -f);
		for(s = (ch ^ 48); isdigit(ch = getchar()); s = (s << 1) + (s << 3) + (ch ^ 48));
		return (s *= f);
	}

	long long n, m, ans, tmp;
	long long tr[N];
	int k, cnt, b[N];
	struct node{ int x, y, num;} a[N];

	bool cmp(node op, node opp){ return op.x == opp.x ? op.y < opp.y : op.x < opp.x;}
	
	inline int lowbit(int x){ return x & (-x);}
	void change(int x, long long val){
		while(x < N){
			tr[x] = std::max(tr[x], val);
			x += lowbit(x);
		}
	}
	inline long long query(int x){
		long long res = 0;
		for(res = std::max(res, tr[x]); (x -= lowbit(x)); res = std::max(res, tr[x]));
		return res;
	}

	inline int main(){
		n = read(); m = read(); k = read();
		for(int i = 1; i <= k; i ++){
			a[i].x = read(); a[i].y = read(); 
			a[i].num = read(); b[i] = a[i].y;
		}

		std::sort(a + 1, a + k + 1, cmp); std::sort(b + 1, b + k + 1);
		cnt = std::unique(b + 1, b + k + 1) - b - 1;
		
		for(int i = 1; i <= k; i ++){
			a[i].y = std::lower_bound(b + 1, b + cnt + 1, a[i].y) - b;
			ans = std::max(ans, tmp = query(a[i].y) + a[i].num);
            		//tmp是当前点的最优解
			change(a[i].y, tmp);
		}

		printf("%lld\n", ans);
		return 0;
	}
}

signed main(){ return Tethys::main();}

完美撒花✿✿ヽ(°▽°)ノ✿

原文
存档评论1 条抓取于