1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| #include <bits/stdc++.h> using namespace std; typedef long long ll; #define endl '\n' const int maxn = 2e5+10; const int maxm = maxn*2; int head[maxn],pa[maxn]; bool loop[maxn],vis[maxn]; struct Edge{ int f,t,next; Edge(int f = 0,int t = 0,int next = 0):f(f),t(t),next(next){} }edge[maxm]; int tcnt,cnt; void addedge(int f,int t){ edge[cnt] = Edge(f,t,head[f]); head[f] = cnt++; } bool ok = 0; void pre(int u,int fa){ if(ok)return; vis[u] = 1; for(int i = head[u];~i;i = edge[i].next){ int v = edge[i].t; if(v == fa or ok)continue; if(vis[v]){ while(u != v){ loop[u] = 1; u = pa[u]; ok = 1; } loop[v] = 1; return; } pa[v] = u; pre(v,u); } } void DFS(int u,int fa){ tcnt++; for(int i = head[u];~i;i = edge[i].next){ int v = edge[i].t; if(v == fa or loop[v])continue; DFS(v,u); } } signed main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ int n; cin >> n; tcnt = 0; ok = 0; cnt = 0; vector<ll>res; for(int i = 0;i <= n;i++)head[i] = -1,loop[i] = 0,pa[i] = vis[i] = 0; for(int i = 1;i <= n;i++){ int f,t; cin >> f >> t; addedge(f,t); addedge(t,f); } pre(1,-1); for(int i = 1;i <= n;i++){ if(loop[i]){ tcnt = 0; DFS(i,-1); res.push_back(tcnt); } } ll ans = 0; for(ll x:res)ans += x*(x-1)/2 + x*(n-x); cout << ans << endl; } return 0; }
|