POJ 3728 The merchant(LCA经典最大值最小值差值

本文介绍了一种解决在N个城市间买卖货物以获取最大利润问题的算法。通过预处理每个城市到其祖先节点的最大和最小价格差,算法能在O(logN)时间内找到任意两点间最大利润。关键在于使用LCA算法和DP技巧,处理复杂的价格变动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

题意:给N个城市,每个城市的货物的价格,现在你可以先买后卖,问Q次询问中,

从起点到终点最多能拿多少利润。

 

做法:

假设起点终点为u,v;祖先为t

我们可以想一下两点间的最大差有多少种情况。

  ①公共祖先到终点的最大值-起点到公共祖先的最小值(u-t,t-v)

  ②起点到公共祖先的最大值-之后起点到公共祖先的最小值(u-t)

  ③公共祖先到终点的最大值-之后终点到公共祖先的最小值(t-v)

除了以上三种,就没有其他情况了。

其中的顺序问题比较难处理,我们可以求出公共祖先后,对起点和终点分别遍历,求出起点边的最小值和终点边的最大值,①就算解决了。

其次那么我们需要维护一个dp_up[u][i],维护u到u节点往上2^i的节点的最大差价 

一个dp_down[u][i],维护u到u节点往下2^i的最大差价。也就是为②③做铺垫。

②则是max(dp_up[u][i],dp_mx[u][i]-pre_mi)

③则是max(dp_down[u][i],pre_mx-dp_mi[u][i])

pre_mi pre_mx分别为上一个节点的最小最大值

 

///                 .-~~~~~~~~~-._       _.-~~~~~~~~~-.
///             __.'              ~.   .~              `.__
///           .'//                  \./                  \\`.
///        .'//                     |                     \\`.
///       .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
///     .'//.-"                 `-.  |  .-'                 "-.\\`.
///   .'//______.============-..   \ | /   ..-============.______\\`.
/// .'______________________________\|/______________________________`.
//#pragma GCC optimize("Ofast")
#pragma comment(linker, "/STACK:102400000,102400000")
//#pragma GCC target(sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx) 
#include <vector>
#include <iostream>
#include <string>
#include <map>
#include <stack>
#include <cstring>
#include <queue>
#include <list>
#include <stdio.h>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cctype>
#include <sstream>
#include <functional>
#include <stdlib.h>
#include <time.h>
#include <bitset>
using namespace std;

#define pi acos(-1)
#define s_1(x) scanf("%d",&x)
#define s_2(x,y) scanf("%d%d",&x,&y)
#define s_3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define s_4(x,y,z,X) scanf("%d%d%d%d",&x,&y,&z,&X)
#define S_1(x) scan_d(x)
#define S_2(x,y) scan_d(x),scan_d(y)
#define S_3(x,y,z) scan_d(x),scan_d(y),scan_d(z)
#define PI acos(-1)
#define endl '\n'
#define srand() srand(time(0));
#define me(x,y) memset(x,y,sizeof(x));
#define foreach(it,a) for(__typeof((a).begin()) it=(a).begin();it!=(a).end();it++)
#define close() ios::sync_with_stdio(0); cin.tie(0);
#define FOR(x,n,i) for(int i=x;i<=n;i++)
#define FOr(x,n,i) for(int i=x;i<n;i++)
#define fOR(n,x,i) for(int i=n;i>=x;i--)
#define fOr(n,x,i) for(int i=n;i>x;i--)
#define W while
#define sgn(x) ((x) < 0 ? -1 : (x) > 0)
#define bug printf("***********\n");
#define db double
#define ll long long
#define mp make_pair
#define pb push_back
typedef long long LL;
typedef pair <int, int> ii;
const int INF=0x3f3f3f3f;
const LL LINF=0x3f3f3f3f3f3f3f3fLL;
const int dx[]={-1,0,1,0,1,-1,-1,1};
const int dy[]={0,1,0,-1,-1,1,-1,1};
const int maxn=1e5+5;
//const int maxx=1e6+10;
const double EPS=1e-8;
const double eps=1e-8;
const int mod=1e9+7;
template<class T>inline T min(T a,T b,T c) { return min(min(a,b),c);}
template<class T>inline T max(T a,T b,T c) { return max(max(a,b),c);}
template<class T>inline T min(T a,T b,T c,T d) { return min(min(a,b),min(c,d));}
template<class T>inline T max(T a,T b,T c,T d) { return max(max(a,b),max(c,d));}
template <class T>
inline bool scan_d(T &ret){char c;int sgn;if (c = getchar(), c == EOF){return 0;}
while (c != '-' && (c < '0' || c > '9')){c = getchar();}sgn = (c == '-') ? -1 : 1;ret = (c == '-') ? 0 : (c - '0');
while (c = getchar(), c >= '0' && c <= '9'){ret = ret * 10 + (c - '0');}ret *= sgn;return 1;}

inline bool scan_lf(double &num){char in;double Dec=0.1;bool IsN=false,IsD=false;in=getchar();if(in==EOF) return false;
while(in!='-'&&in!='.'&&(in<'0'||in>'9'))in=getchar();if(in=='-'){IsN=true;num=0;}else if(in=='.'){IsD=true;num=0;}
else num=in-'0';if(!IsD){while(in=getchar(),in>='0'&&in<='9'){num*=10;num+=in-'0';}}
if(in!='.'){if(IsN) num=-num;return true;}else{while(in=getchar(),in>='0'&&in<='9'){num+=Dec*(in-'0');Dec*=0.1;}}
if(IsN) num=-num;return true;}

void Out(LL a){if(a < 0) { putchar('-'); a = -a; }if(a >= 10) Out(a / 10);putchar(a % 10 + '0');}
void print(LL a){ Out(a),puts("");}
//freopen( "in.txt" , "r" , stdin );
//freopen( "data.txt" , "w" , stdout );
//cerr << "run time is " << clock() << endl;


int up[maxn][23],deep[maxn];
int dp_mx[maxn][23],dp_mi[maxn][23];
int dp_up[maxn][23],dp_down[maxn][23];
int cnt,head[maxn];
int n,m,q,a[maxn];
struct node {
    int to, next, w;
}e[maxn<<1];
void init() {
    cnt = 0; me(head, -1);
}
void add(int u, int v, int w) {
    e[cnt] = node{v, head[u], w};
    head[u] = cnt++;
}

void dfs(int u,int fa,int d) {
	deep[u]=deep[fa]+1;
	up[u][0]=fa;
	dp_mx[u][0]=max(a[u],a[fa]);
	dp_mi[u][0]=min(a[u],a[fa]);
	dp_up[u][0]=max(0,a[fa]-a[u]);
	dp_down[u][0]=max(0,a[u]-a[fa]);
	for(int i=1;i<20;i++) {
		int f=up[u][i-1];
		up[u][i]=up[f][i-1];
		dp_mx[u][i]=max(dp_mx[f][i-1],dp_mx[u][i-1]);
		dp_mi[u][i]=min(dp_mi[f][i-1],dp_mi[u][i-1]);
		dp_up[u][i]=max(dp_up[f][i-1],dp_up[u][i-1],dp_mx[f][i-1]-dp_mi[u][i-1]);
		dp_down[u][i]=max(dp_down[f][i-1],dp_down[u][i-1],dp_mx[u][i-1]-dp_mi[f][i-1]);
	}
    for(int i=head[u];~i;i=e[i].next) {
    	int to=e[i].to;
    	if(to==fa) continue;
    	dfs(to,u,d+1);
	}
}

int LCA_BZ(int u,int v) {
    int mx = 0;
    if(deep[u] < deep[v]) swap(u,v);
    int k = deep[u] - deep[v];
    for(int i = 19 ; i >= 0 ; i --) {
        if((1<<i) & k) {
            u = up[u][i];
        }
    }
    if(u == v) return u;
    for(int i = 19 ; i >= 0 ; i --) {
        if(up[u][i] != up[v][i]){
            u = up[u][i];
            v = up[v][i];
        }
    }
    return up[u][0];
}

ii tup(int u,int k) {
	int ans=0,mi=INF,pre_mi=INF;
	for(int i=19;i>=0;i--) {
		if(k&(1<<i)) {
			mi=min(mi,dp_mi[u][i]);
			ans=max(ans,dp_up[u][i],dp_mx[u][i]-pre_mi);
			pre_mi=min(pre_mi,dp_mi[u][i]);
			u=up[u][i];
		}
	}
	return {ans,mi};
}

ii down(int u,int k) {
	int ans=0,mx=0,pre_mx=0;
	for(int i=19;i>=0;i--) {
		if(k&(1<<i)) {
			mx=max(mx,dp_mx[u][i]);
			ans=max(ans,dp_down[u][i],pre_mx-dp_mi[u][i]);
			pre_mx=max(pre_mx,dp_mx[u][i]);
			u=up[u][i];
		}
	}
	return {ans,mx};
}
			
void solve() {
	s_1(n);
	init();
	FOR(1,n,i) s_1(a[i]);
	FOr(1,n,i) {
		int u,v;
		s_2(u,v);
		add(u,v,1);
		add(v,u,1);
	}
	for(int i=0;i<20;i++) 
		dp_mx[1][i]=dp_mi[1][i]=a[1];
	dfs(1,-1,0);
	s_1(q);
	W(q--) {
		int u,v;
		s_2(u,v);
		int ans=0,f=LCA_BZ(u,v);
		ii t1=tup(u,deep[u]-deep[f]);
		ii t2=down(v,deep[v]-deep[f]);
		ans=max(t1.first,t2.first,t2.second-t1.second);
		//t1.first 为起点到公共祖先 t2.first为公共祖先到终点   最后为公共祖先到终点的最大值-起点到公共祖先的最小值 
		print(ans);
	}
}
 		
int main() {
    //freopen( "1.in" , "r" , stdin );
    //freopen( "1.out" , "w" , stdout );
    int t=1;
    //init();
    //s_1(t);
    for(int cas=1;cas<=t;cas++) {
        //printf("Case #%d: ",cas);
        solve();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值