Main idea:
Give you n points and n edges, find the number of simple paths in the graph
Question idea:
n points and n edges, then there must be a ring in the graph
Take this picture as an example, we divide the relationship between two points into 4 types:
1. Both points are on the ring, and the number of simple paths is 2
(for example, 2 and 5)
2. One point is on the ring and the other is not on the ring Above, the number of simple paths is 2
(for example, 2 and 6)-but it cannot be 2 and 3 or 2 and 4 (this is case 3)
3. Two points are under the same subtree (take the ring as the root) Simple paths The number is 1
(for example, 2 and 3 or 3 and 1)
4. Two points are under different subtrees (take the ring as the root) The number of simple paths is 2
(for example, 7 and 3)
It can be found that the number of simple paths between any two points is either 1 or 2
and 2 is mostly the case.
Then you can assume that all 4 cases are 2, and you only need to figure out the case 3 and subtract it.
ans = (n-1)*n-(k-1)*k/2;
k is the total number of nodes in the subtree rooted at any child node on the ring.
Mathematical symbols will not be used (escape)
Code:
void top_sort() {
cnt=0;
queue<int>q;
mst(vis,0);
mst(vi,0);
for(int i=1 ; i<=n ; i++) if(d[i]==1) q.push(i);
while(q.size()) {
int dian = q.front();
q.pop();
vi[dian] = 1;
for(int v:e[dian]) {
d[v]--;
if(d[v]==1) q.push(v);
}
}
rep(i,1,n) if(vi[i]==0) huan[++cnt] = i,vis[i] = 1;
}
void dfs(int u,int p) {
for(int v:e[u]) {
if(v==p||vis[v]) continue;
dfs(v,u);
s[p]+=s[v];
}
}
int main() {
int _= read();
while(_--) {
n=read(),mst(d,0);
rep(i,1,n) e[i].clear(),s[i] =1;
for(int i=1 ; i<=n ; i++) {
int u,v;
u=read(),v=read();
e[u].push_back(v);
e[v].push_back(u);
d[u]++,d[v]++;
}
top_sort();
ll ans = (n-1)*n*1ll;
for(int i=1 ; i<=cnt; i++) {
int u = huan[i];
dfs(u,u);
ans -=(s[u]-1)*s[u]/2ll;
}
printf("%lld\n",ans);
}
return 0;
}