Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 1520 | Accepted: 434 |
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.
Each of the next N lines contains wi the goods' price in each city.
Each of the next N-1 lines contains labels of two cities, describing a road between the two cities.
The next line contains Q, the number of paths.
Each of the next Q lines contains labels of two cities, describing a path. The cities are numbered from 1 to N.
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
#include<cstdio>
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
#define swap(a,b) (a^=b,b^=a,a^=b)
using namespace std;
const int mm=333333;
const int mn=55555;
int s[mm],t[mm],d[mm],p[mm],ans[mm];
int h[mn]={0},q[mn]={0},g[mn]={0},f[mn],mx[mn],mi[mn],up[mn]={0},dw[mn]={0};
bool vis[mn]={0};
int i,j,k,n,m,e;
inline void add(int u,int v,int c,int h[])
{
s[e]=u,t[e]=v,d[e]=c,p[e]=h[u],h[u]=e++;
s[e]=v,t[e]=u,d[e]=-c,p[e]=h[v],h[v]=e++;
}
int find(int x)
{
if(f[x]==x)return x;
int y=f[x];
f[x]=find(f[x]);
up[x]=max(mx[y]-mi[x],max(up[x],up[y]));
dw[x]=max(mx[x]-mi[y],max(dw[x],dw[y]));
mx[x]=max(mx[x],mx[y]);
mi[x]=min(mi[x],mi[y]);
return f[x];
}
void tarjan(int u)
{
int i,v,x,y;
vis[f[u]=u]=1;
for(i=q[u];i;i=p[i])
if(vis[v=t[i]])
v=find(v),t[e]=i,p[e]=g[v],g[v]=e++;
for(i=h[u];i;i=p[i])
if(!vis[v=t[i]])tarjan(v),f[v]=u;
for(i=g[u];i;i=p[i])
{
v=t[i],x=s[v],y=t[v],find(x);
if(d[v]<0)swap(x,y),v=-d[v];
else v=d[v];
ans[v]=max(mx[y]-mi[x],max(up[x],dw[y]));
}
}
inline void get(int &a)
{
char c;
while((c=getchar())<'0'||c>'9');
for(a=0;c>='0'&&c<='9';c=getchar())a=a*10+c-'0';
}
void out(int x)
{
if(x>9)out(x/10);
putchar(x%10+'0');
}
int main()
{
for(get(n),i=1; i<=n; ++i)get(mx[i]),mi[i]=mx[i];
for(e=k=1; k<n; ++k)get(i),get(j),add(i,j,0,h);
for(get(m),k=1; k<=m; ++k)get(i),get(j),add(i,j,k,q);
tarjan(1);
for(i=1; i<=m; ++i)out(ans[i]),puts("");
return 0;
}