#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ins insert
#define int long long
#define vii vector<int>
#define pii pair<int,int>
#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
const int N=200001;
vector<int>graph[N];
vector<bool>check(N,false);
vector<int>parent(N,-1);
vector<int>subTreeSize(N,0);
int cycleVertex=-1;
int cycleStart=-1;
int cycleStop=-1;
vector<int>cycleGraph[N];
vector<bool>cycleCheck(N,false);

void print(vii &a){
    for(int i=0;i<a.size();i++)
    {
        cout<<a[i]<<" ";
    }cout<<endl;
}

int dfs2(int v)
{
    cycleCheck[v]=true;
    int tot=1;
    for(int i=0;i<cycleGraph[v].size();i++)
    {
        int child=cycleGraph[v][i];
        if(cycleCheck[child]==false)
        {
            tot+=dfs2(child);
        }
    }
    return tot;
}
void clear(int n)
{
    cycleVertex=-1;
    cycleStart=-1;
    cycleStop=-1;
    for(int i=1;i<=n;i++)
    {
        graph[i].clear();
        parent[i]=-1;
        check[i]=false;
        cycleCheck[i]=false;
        subTreeSize[i]=0;
        cycleGraph[i].clear();
    }
}
void dfs1(int v)
{
    check[v]=true;
    if(cycleVertex!=-1)return;
    for(int i=0;i<graph[v].size();i++)
    {
        if(cycleVertex!=-1)return;
        int child=graph[v][i];
        if(check[child]==false)
        {
            parent[child]=v;
            dfs1(child);
        }
        else if(check[child]==true && parent[v]!=child)
        {
            cycleStart=v;
            cycleStop=child;
            cycleVertex=1;
            return;
        }
    }
}
void solve()
{
    int n;cin>>n;
    vector<pii>storeEdges;
    for(int i=0;i<n;i++)
    {
        int x,y;cin>>x>>y;
        graph[x].pb(y);
        graph[y].pb(x);
        storeEdges.pb(mp(x,y));
    }
    parent[1]=1;
    dfs1(1);
    vii getCycle;
    
    while(cycleStart!=cycleStop)
    {
        getCycle.pb(cycleStart);
        cycleStart=parent[cycleStart];
    }
    getCycle.pb(cycleStart);
    //print(getCycle);

    for(int i=0;i<getCycle.size();i++)
    {
        cycleCheck[getCycle[i]]=true;
    }

    //Add without cycle Edges
    for(int i=0;i<storeEdges.size();i++)
    {
        int u=storeEdges[i].fi;
        int v=storeEdges[i].se;
        //Cycle Edge
        if(cycleCheck[u]==true && cycleCheck[v]==true)continue;
        else
        {
            cycleGraph[u].pb(v);
            cycleGraph[v].pb(u);
        }
    }
    int ans=n*(n-1);
    for(int i=0;i<getCycle.size();i++)
    {
       int v=getCycle[i];
       subTreeSize[v]=dfs2(v); 
       int x=subTreeSize[v];
       ans=ans-(x*(x-1))/2;
    }
    cout<<ans<<endl;
    clear(n);
}
int32_t main()
{
    FAST;
    int t;cin>>t;
    while(t--)
    {
        solve();
    }
    return 0;
}