|
The merchant
Description There are N cities in a country, and there is one and only one simple path between each pair of cities. A merchant has chosen some paths and wants to earn as much money as possible in each path. When he move along a path, he can choose one city to buy some goods and sell them in a city after it. The goods in all cities are the same but the prices are different. Now your task is to calculate the maximum possible profit on each path. Input The first line contains N, the number of cities. 1 ≤ N, wi, Q ≤ 50000 Output The output contains Q lines, each contains the maximum profit of the corresponding path. If no positive profit can be earned, output 0 instead. Sample Input 4 1 5 3 2 1 3 3 2 3 4 9 1 2 1 3 1 4 2 3 2 1 2 4 3 1 3 2 3 4 Sample Output 4 2 2 0 0 0 0 2 0 Source
POJ Monthly Contest – 2009.04.05, GaoYihan
|
题意:
一棵树,q个询问,问你x到y,买进卖出最多赚多少。(只能先买后卖,不能走回头)。
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
const int maxn=50000+013;
int val[maxn];
int head[maxn],nxt[maxn<<1],to[maxn<<1],cnt=0;
int fa[maxn][20],Max[maxn][20],Min[maxn][20],p1[maxn][20],p2[maxn][20];
int n,d[maxn];
void add(int u,int v)
{
nxt[cnt]=head[u];
to[cnt]=v;
head[u]=cnt++;
}
void dfs(int u,int pre)
{
for(int i=head[u];~i;i=nxt[i]){
int v=to[i];
if(v==pre) continue;
d[v]=d[u]+1;
fa[v][0]=u;
Max[v][0]=max(val[v],val[u]);
Min[v][0]=min(val[v],val[u]);
p1[v][0]=max(0,val[u]-val[v]);
p2[v][0]=max(0,val[v]-val[u]);
dfs(v,u);
}
}
void lcainit()
{
for(int i=1;(1<<i)<=n;i++){
for(int j=1;j<=n;j++){
fa[j][i]=fa[fa[j][i-1]][i-1];
if(fa[j][i]==0) continue;
Max[j][i]=max(Max[j][i-1],Max[fa[j][i-1]][i-1]);
Min[j][i]=min(Min[j][i-1],Min[fa[j][i-1]][i-1]);
p1[j][i]=max(p1[j][i-1],p1[fa[j][i-1]][i-1]);
p2[j][i]=max(p2[j][i-1],p2[fa[j][i-1]][i-1]);
p1[j][i]=max(p1[j][i],Max[fa[j][i-1]][i-1]-Min[j][i-1]);
p2[j][i]=max(p2[j][i],Max[j][i-1]-Min[fa[j][i-1]][i-1]);
}
}
}
int lca(int a,int b)
{
if(d[a]<d[b]) swap(a,b);
int dis=d[a]-d[b];
for(int i=0;(1<<i)<=dis;i++){
if(1<<i&dis) a=fa[a][i];
}
if(a==b) return a;
for(int i=(int)log2(n);i>=0;i--){
if(fa[a][i]!=fa[b][i])
a=fa[a][i],b=fa[b][i];
}
return fa[a][0];
}
int main()
{
int u,v;
scanf("%d",&n);
for(int i=1;i<=n;i++) {
scanf("%d",&val[i]);
head[i]=-1;
}
for(int i=1;i<n;i++){
scanf("%d %d",&u,&v);
add(u,v);
add(v,u);
}
int q;scanf("%d",&q);
dfs(1,0);
lcainit();
while(q--){
scanf("%d %d",&u,&v);
int t=lca(u,v);
int ma=0,mi=0x3f3f3f3f;
int ans=0;
int dis=d[u]-d[t];
for(int i=0;(1<<i)<=dis;i++){
if(1<<i&dis){
ans=max(ans,Max[u][i]-mi);
ans=max(ans,p1[u][i]);
mi=min(mi,Min[u][i]);
u=fa[u][i];
}
}
dis=d[v]-d[t];
for(int i=0;(1<<i)<=dis;i++){
if(1<<i&dis){
ans=max(ans,ma-Min[v][i]);
ans=max(ans,p2[v][i]);
ma=max(ma,Max[v][i]);
v=fa[v][i];
}
}
printf("%d\n",max(ans,ma-mi));
}
return 0;
}

786

被折叠的 条评论
为什么被折叠?



