import std.conv, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.container, std.math, std.numeric, std.range, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } void chmin(T)(ref T t, in T f) { if (t > f) t = f; } void chmax(T)(ref T t, in T f) { if (t < f) t = f; } int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(as.length); for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; } int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a < val)); } int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); } enum LIM_LOGN = 17; int N; int[] U, V; int Q; int[] A, B; int[][] G; int[][] par; int[] dep; void dfs(int u, int p, int d) { par[0][u] = p; dep[u] = d; foreach (v; G[u]) { if (v != p) { dfs(v, u, d + 1); } } } int getLCA(int u, int v) { foreach_reverse (e; 0 .. LIM_LOGN) { if (dep[u] - (1 << e) >= dep[v]) { u = par[e][u]; } if (dep[v] - (1 << e) >= dep[u]) { v = par[e][v]; } } foreach_reverse (e; 0 .. LIM_LOGN) { if (par[e][u] != par[e][v]) { u = par[e][u]; v = par[e][v]; } } if (u != v) { u = par[0][u]; v = par[0][v]; } return u; } long[] sum, sumL; void dfs1(int u) { foreach (v; G[u]) { if (v != par[0][u]) { dfs1(v); sum[u] += sum[v]; } } } void main() { try { for (; ; ) { N = readInt(); U = new int[N - 1]; V = new int[N - 1]; foreach (i; 0 .. N - 1) { U[i] = readInt() - 1; V[i] = readInt() - 1; } Q = readInt(); A = new int[Q]; B = new int[Q]; foreach (q; 0 .. Q) { A[q] = readInt() - 1; B[q] = readInt() - 1; } G = new int[][N]; foreach (i; 0 .. N - 1) { G[U[i]] ~= V[i]; G[V[i]] ~= U[i]; } par = new int[][](LIM_LOGN, N); dep = new int[N]; const rt = 0; dfs(rt, rt, 0); foreach (e; 1 .. LIM_LOGN) { foreach (u; 0 .. N) { par[e][u] = par[e - 1][par[e - 1][u]]; } } sum = new long[N]; sumL = new long[N]; foreach (q; 0 .. Q) { const l = getLCA(A[q], B[q]); sum[A[q]] += 1; sum[B[q]] += 1; sum[l] -= 2; sumL[l] += 1; } dfs1(rt); long ans; foreach (u; 0 .. N) { const c = sum[u] + sumL[u]; ans += c * (c + 1) / 2; debug { writeln(u, " ", c); } } writeln(ans); } } catch (EOFException e) { } }