← Home
For problem statement at 1000-1999/1000-1099/1000-1009/1000/problemG.txt this is a correct solution, but verifier at 1000-1999/1000-1099/1000-1009/1000/verifierG.go ends with All tests passed! can you fix the verifier? package main

import (
	"bufio"
	"fmt"
	"os"
)

type Edge struct {
	to int
	w  int64
}

var (
	a       []int64
	adj     [][]Edge
	dp_down []int64
	f_down  []int64
	dp_up   []int64
	V       []int64
	Pref    []int64
	depth   []int
	up      [][]int
)

func max(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

func dfs1(u, p int, d int, w_p int64) {
	depth[u] = d
	up[u][0] = p
	for i := 1; i < 20; i++ {
		up[u][i] = up[up[u][i-1]][i-1]
	}

	dp_down[u] = 0
	for _, e := range adj[u] {
		if e.to != p {
			dfs1(e.to, u, d+1, e.w)
			dp_down[u] += f_down[e.to]
		}
	}
	if u != 1 {
		f_down[u] = max(0, a[u]+dp_down[u]-2*w_p)
	}
}

func dfs2(u, p int, w_p int64) {
	if u == 1 {
		dp_up[u] = 0
		V[u] = a[u] + dp_down[u]
		Pref[u] = 0
	} else {
		dp_up[u] = max(0, a[p]+dp_down[p]-f_down[u]+dp_up[p]-2*w_p)
		V[u] = a[u] + dp_down[u] + dp_up[u]
		E_u := f_down[u] + dp_up[u] + w_p
		W_u := V[u] - E_u
		Pref[u] = Pref[p] + W_u
	}

	for _, e := range adj[u] {
		if e.to != p {
			dfs2(e.to, u, e.w)
		}
	}
}

func getLCA(u, v int) int {
	if depth[u] < depth[v] {
		u, v = v, u
	}
	diff := depth[u] - depth[v]
	for i := 0; i < 20; i++ {
		if (diff & (1 << i)) != 0 {
			u = up[u][i]
		}
	}
	if u == v {
		return u
	}
	for i := 19; i >= 0; i-- {
		if up[u][i] != up[v][i] {
			u = up[u][i]
			v = up[v][i]
		}
	}
	return up[u][0]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	const maxCapacity = 10 * 1024 * 1024
	buf := make([]byte, maxCapacity)
	scanner.Buffer(buf, maxCapacity)
	scanner.Split(bufio.ScanWords)

	nextInt := func() int {
		scanner.Scan()
		res := 0
		for _, v := range scanner.Bytes() {
			res = res*10 + int(v-'0')
		}
		return res
	}

	nextInt64 := func() int64 {
		scanner.Scan()
		var res int64 = 0
		for _, v := range scanner.Bytes() {
			res = res*10 + int64(v-'0')
		}
		return res
	}

	if !scanner.Scan() {
		return
	}
	n := 0
	for _, v := range scanner.Bytes() {
		n = n*10 + int(v-'0')
	}
	q := nextInt()

	a = make([]int64, n+1)
	for i := 1; i <= n; i++ {
		a[i] = nextInt64()
	}

	adj = make([][]Edge, n+1)
	for i := 0; i < n-1; i++ {
		u := nextInt()
		v := nextInt()
		w := nextInt64()
		adj[u] = append(adj[u], Edge{v, w})
		adj[v] = append(adj[v], Edge{u, w})
	}

	dp_down = make([]int64, n+1)
	f_down = make([]int64, n+1)
	dp_up = make([]int64, n+1)
	V = make([]int64, n+1)
	Pref = make([]int64, n+1)
	depth = make([]int, n+1)

	up = make([][]int, n+1)
	for i := 1; i <= n; i++ {
		up[i] = make([]int, 20)
	}

	dfs1(1, 1, 0, 0)
	dfs2(1, 1, 0)

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	for i := 0; i < q; i++ {
		qu := nextInt()
		qv := nextInt()
		lca := getLCA(qu, qv)
		ans := Pref[qu] + Pref[qv] - 2*Pref[lca] + V[lca]
		fmt.Fprintln(out, ans)
	}
}