//LIBRARIES
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <chrono>
//MACROS
#define LOCAL
#define _crt_secure_no_warnings
#define FREEELO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define pb push_back
#define mp make_pair
#define INF 0x3F3F3F3F
#define MAX 200010
#define MAXLL 1000000000000000000LL
#define MOD 1000000007
#define LOGMAX 20
#define ALPHABET 128
#define loop(i, n) for (int i = 1; i <= (n); i++)
#define loop0(i, n) for (int i = 0; i < (n); i++)
#define sz(x) (int)x.size()
#define all(v) v.begin(), v.end()
#define all1(v) v.begin(), v.end()
#define F first
#define S second
#define EPS 1e-7
using namespace std;
using namespace std::chrono;
//TYPE DEFINITIONS
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
typedef pair<ll, ll> llll;
typedef pair<int, int> ii;
typedef unordered_map<int, int> umii;
typedef unordered_map<ll, ll> umll;
typedef unordered_set<int> usi;
typedef unordered_multiset<int> usmi;
//main exec
vector<vector<int> > g;
vector<int> used, top;
umii check;
int flag, cnt;
void dfs(int v, int prev = -1){
    if (flag) return;
    top.pb(v);
    used[v] = 1;
    for (int &to : g[v]){
        if (used[to] && to != prev) {
            flag = to; return;
        }
        else if (used[to] == 0){
            dfs(to, v);
            if (flag) return;
        }
    }
    top.pop_back();
}
void dfs_c(int v, int prev = -1){
    cnt++;
    for (int &to : g[v]){
        if (!check[to] && to != prev) dfs_c(to, v);
    }
}

int main(){
    FREEELO
    int t; cin >> t;
    while(t--){
        int n; cin >> n;
        g.clear(); g.resize(n + 1);
        used.clear(); top.clear();
        used.resize(n + 1); flag = 0;
        loop(i, n){
            int u, v; cin >> u >> v;
            g[u].pb(v); g[v].pb(u);
        }
        dfs(1); vector<int> cycle;
        for (int i = top.size() - 1; i >= 0; i--){
            if (top[i] == flag) {cycle.pb(flag); break;}
            cycle.pb(top[i]); check[top[i]]++;
        }
        check[flag]++;
        reverse(all(cycle));
        ll ans = 0;
        for (int &v : cycle){
            cnt = 0;
            dfs_c(v);
            ans += (((cnt - 1) * 1LL * cnt) / 2 + cnt * 1LL * (n - cnt));
        }
        cout << ans << '\n';
        check.clear();
    }
}