#include <bits/stdc++.h>

#pragma GCC optimize("O3")
#pragma GCC target("avx,avx2")

using namespace std;

#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define len(a) int(a.size())

using ll = long long;

template<typename T>
using PQ = priority_queue<T, vector<T>, greater<>>;

pair<int, int> diam(const vector<vector<int>> &g) {
    auto dfs = [&](auto self, int v, int p, int d) -> pair<int, int> {
        pair<int, int> res = {d, v};
        for (int i : g[v]) {
            if (i != p) {
                res = max(res, self(self, i, v, d + 1));
            }
        }
        return res;
    };
    int v1 = dfs(dfs, 0, -1, 0).second;
    int v2 = dfs(dfs, v1, -1, 0).second;
    return {v1, v2};
}

vector<int> dist(const vector<vector<int>> &g) {
    auto dfs = [&](auto self, int v, int p, int d, vector<int> &ans) -> void {
        ans[v] = d;
        for (int i : g[v]) {
            if (i != p) {
                self(self, i, v, d + 1, ans);
            }
        }
    };

    auto [v1, v2] = diam(g);
    vector<int> ans1(len(g)), ans2(len(g)), ans(len(g));
    dfs(dfs, v1, -1, 0, ans1);
    dfs(dfs, v2, -1, 0, ans2);
    for (int i = 0; i < len(g); ++i) {
        ans[i] = max(ans1[i], ans2[i]);
    }
    return ans;
}

void solve() {
    int n, k;
    cin >> n >> k;
    vector<vector<int>> g1(n), g2(n);
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        cin >> a >> b;
        g1[a - 1].push_back(b - 1);
        g1[b - 1].push_back(a - 1);
    }
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        cin >> a >> b;
        g2[a - 1].push_back(b - 1);
        g2[b - 1].push_back(a - 1);
    }
    vector<int> ans1 = dist(g1), ans2 = dist(g2);
    sort(all(ans1));
    sort(all(ans2));
    int res1 = *max_element(all(ans1));
    int res2 = *max_element(all(ans2));
    if (res1 > k || res2 > k) {
        cout << 0 << '\n';
        return;
    }

    // ans1[i] + ans2[j] < k
    ll ans = 0;
    int it = n - 1;
    for (int i = 0; i < n; ++i) {
        while (it >= 0 && ans1[i] + ans2[it] + 1 > k) {
            --it;
        }
        ans += it + 1;
    }
    cout << ans << '\n';
}

int main(int argc, char* argv[]) {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    cin >> t;
    while (t--) solve();
}