题意:
给出一棵树,有点权,5W次询问从a走到b交易一件物品能获得的最大利润(即在某个节点买入一件物品,在后面的节点卖出)。
正确理解题意花了一天多,泪奔。
解法:
设a,b的LCA为c,则答案来自a->c,c->b,或者在ac段买入在cb段卖出。容易想到信息是可以合并的,那么不妨在Tarjan用并查集求出一个询问的LCA后,顺便用并查集把路径的信息合并。TarjanLCA求lca(a,b)的过程中会先把a一路Find()到lca节点,为了得到b到lca的信息,只需要把这个询问放在dfs返回到lca节点时再处理即可。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
#define rep(i,x) for (int i = 0; i < (int)x.size(); i ++)
const int N = 55555,INF = 0x3f3f3f3f;
int n,pa[N],w[N],ans[N];
struct INFO {
int vmax,vmin;
int dwmax,dwmin;
void show() {
printf("show :: %d %d %d %d\n\n",vmax,vmin,dwmax,dwmin);
}
};
INFO node[N];
vector<PII> qnode[N];
vector<pair<pair<int,int>,int> > sol[N];
vector<int> edge[N];
bool vis[N];
void tomax(int &a,int b) { if (a<b) a=b; }
void tomin(int &a,int b) { if (a>b) a=b; }
int Find(int x) {
if (pa[x]==x) return x;
int y = pa[x];
pa[x] = Find(pa[x]);
tomax(node[x].dwmax,max(node[x].vmax-node[y].vmin,node[y].dwmax));
tomin(node[x].dwmin,min(node[x].vmin-node[y].vmax,node[y].dwmin));
tomax(node[x].vmax,node[y].vmax);
tomin(node[x].vmin,node[y].vmin);
return pa[x];
}
void tarjan(int u) {
pa[u] = u;
vis[u] = true;
node[u] = (INFO) {w[u],w[u],0,0};
rep(i,qnode[u]) {
int v = qnode[u][i].first;
int id = qnode[u][i].second;
bool flag = false;
if (v<0) v = -v, flag = true;
if (vis[v]) {
Find(v);
if (flag) sol[pa[v]].push_back(make_pair(make_pair(u,v),id));
else sol[pa[v]].push_back(make_pair(make_pair(v,u),id));
}
}
rep(i,edge[u]) {
int v = edge[u][i];
if (!vis[v]) {
tarjan(v);
pa[v] = u;
}
}
rep(i,sol[u]) {
int a = sol[u][i].first.first;
int b = sol[u][i].first.second;
int id = sol[u][i].second;
Find(a);
Find(b);
ans[id] = max(node[b].vmax-node[a].vmin,max(node[b].dwmax,-node[a].dwmin));
}
}
int main() {
int a,b;
scanf("%d",&n);
for (int i = 1; i <= n; i ++) scanf("%d",&w[i]);
for (int i = 0; i < n-1; i ++) {
scanf("%d%d",&a,&b);
edge[a].push_back(b);
edge[b].push_back(a);
}
int nq;
scanf("%d",&nq);
for (int i = 0; i < nq; i ++) {
scanf("%d%d",&a,&b);
qnode[a].push_back(PII(-b,i));
qnode[b].push_back(PII(a,i));
}
tarjan(1);
for (int i = 0; i < nq; i ++) printf("%d\n",ans[i]);
return 0;
}