#include #include #include #include #include #include #include #define pii pair #define xx first #define yy second #pragma comment(linker, "/STACK:102400000,102400000") #define LL long long using namespace std; const int N = 101000, K = 110, INF = 1e9; vector g[N]; int d[N], a[N]; pii dfs (int u, int fa, int c) { // int flag = 0; if (a[u]) return pii (max (0, a[u]), min (INF, a[u])); pii res = pii (0, 1e9); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (v == fa) continue; pii tmp = dfs (v, u, c); if (tmp.xx == -1) return pii (-1, 0); res.xx = max (res.xx, tmp.xx - c); res.yy = min (res.yy, tmp.yy + c); // res.xx = max (res.xx, tmp.xx); // if (tmp) // flag = 1; } // if (!flag) return res; if (res.xx > res.yy) return pii (-1, 0); // cout << u << ' '<< res.xx << ' ' << res.yy << endl; return res; } int main () { // freopen ("in.txt", "r", stdin); int T; cin >>T; while (T--) { int n, k, u, v; cin >> n >> k; for (int i = 1; i <= n; i++) { d[i] = a[i] = 0; g[i].clear(); } for (int i = 1; i < n; i++) { scanf ("%d%d", &u, &v); g[u].push_back (v); g[v].push_back (u); d[u]++; d[v]++; } for (int i = 1; i <= k; i++) { scanf ("%d%d", &u, &v); a[u] = v; } if (n == 2) { if (k == 1) cout << 0 << endl; else cout << abs (a[1] - a[2]) << endl; continue; } int rt = 0; for (int i = 1; i<= n; i++) if (d[i] != 1) { rt = i; break; } // cout << rt << endl; int l = -1, r = 1e9; // pii tmp = dfs (rt, 0, 1); // cout << tmp.xx << ' ' << tmp.yy << endl; while (l + 1 < r) { int m = (l + r) / 2; if (dfs (rt, 0, m).xx != -1) r = m; else l = m; } cout << r << endl; } }