DIV3E 基環樹
阿新 • • 發佈:2021-01-12
#include<bits/stdc++.h> using namespace std; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define rush! ios::sync_with_stdio(false);cin.tie(0); const int inf = 0x3f3f3f3f; const long long linf = 0x3f3f3f3f3f3f3f3f; vector<int >g[200005]; typedef long long ll; const int N=200005; ll f[N];//void init(ll n){ // f[0]=1; // for(ll i=1;i<=n;++i){ // f[i]=f[i-1]*i; // } //} ll C(ll n){ if( 2>n) return 0; return n*(n-1)/2; } int ind; int dfn[N],fa[N]; int loop[N],cnt; int vis[N]; void loops(int u){ dfn[u]=++ind; for(auto i:g[u]){ if(i==fa[u])continue;if(dfn[i]){ if(dfn[i]<dfn[u])continue; loop[++cnt]=i; vis[i]=1; for(;i!=u;i=fa[i]){ loop[++cnt]=fa[i]; vis[fa[i]]=1; } return ; } else{ fa[i]=u; loops(i); } } } ll dfs(int u,int fa){ ll res=1; for(auto i:g[u]){ if(i!=fa&&!vis[i]){ res+=dfs(i,u); } } return res; } void solve(){ int n; cin>>n; for(int i=1;i<=n;i++){ ind=0; dfn[i]=0,fa[i]=0; loop[i]=0; cnt=0; vis[i]=0; g[i].clear(); } for(int i=1;i<=n;i++){ int x,y; cin>>x>>y; g[x].push_back(y); g[y].push_back(x); } ll ans=C(n)*2; // cout<<ans<<endl; loops(1); for(int i=1;i<=cnt;i++){ ans-=C(dfs(loop[i],-1)); } cout<<ans<<endl; } int main(){ int t; cin>>t; // cout<<C(5,2); while(t--){ solve(); } }