#P105. Link, Cut, Wither

Link, Cut, Wither

题目描述

给定一棵 nn 个点的树 T=(V,E)T=(V,E),对每个点 ii 有点权 gig_i,对于树上不同的点 a,b,cVa,b,c\in V,构成的有序三元组 (a,b,c)(a,b,c),按如下规则定义其价值 f(a,b,c)f(a,b,c)

  • xx 为树上令 dist(x,a)dist(x,b)dist(x,c)\mathrm{dist}(x,a)-\mathrm{dist}(x,b)-\mathrm{dist}(x,c) 最大的点(如有多个,取编号最小的),其中 dist(x,y)\mathrm{dist}(x,y) 表示树上点 x,yx,y 之间简单路径经过的边数;
  • f(a,b,c)=dist(x,a)+dist(x,b)+dist(x,c)f(a,b,c)=\mathrm{dist}(x,a)+\mathrm{dist}(x,b)+\mathrm{dist}(x,c)

给定 dd,你需要在树中选出三个不同的点 L,C,WL,C,W,满足 gLgCd,gLgWd|g_L-g_C|\ge d,|g_L-g_W|\ge d,输出 f(L,C,W)f(L,C,W) 的最大值,无解输出 1-1

输入格式

第一行,输入两个整数,表示 n,dn, d (3n5×105,1ai,d109)(3 \le n \le 5\times 10^5, 1 \le a_i, d \le 10^9)

第二行,输入 nn 个整数,表示 g1,g2,,gng_1, g_2, \ldots, g_n (1gi109)(1\le g_i \le 10^9)

以下 n1n-1 行,每行输入两个整数 u,vu,v ,表示一条树上的边。

输出格式

输出一行一个整数,表示 f(L,C,W)f(L, C, W) 的最大值;如果无解,输出 1-1

输入输出样例 #1

输入 #1

6 5
4 3 13 3 14 2 
1 2
1 3
1 4
1 5
2 6

输出 #1

6