Codeforces Round #686 (Div. 3)E. Number of Simple Paths
题意:
给一个有 n n n个结点的基环树,求简单路径个数。
思路:
对于一个
n
n
n个结点的无根树,其简单路径个数是
C
n
2
=
n
(
n
−
1
)
2
C_{n}^2=\cfrac{n(n-1)}{2}
Cn2=2n(n−1),因为你可以选取任意两个不同的结点,他们直接都有一条简单路径。
现在加上一条边
e
e
e,对于每一对结点,都有两种不同的路径到达。
考虑对于环上一个结点
u
u
u,其子树之间不能通过新增的路径
e
e
e产生新的简单路径,因为要经过路径
e
e
e的话,必然会经过
u
u
u两次。所以对于大小为
k
k
k的子树,要减去
k
(
k
−
1
)
2
\cfrac{k(k-1)}{2}
2k(k−1)。
我们通过拓扑排序可以得到环上的点,他们最终的度数
i
n
u
=
2
in_u=2
inu=2,同时也可以算出子树的大小
s
z
u
sz_u
szu。
所以答案为:
n
(
n
−
1
)
−
∑
u
=
1
,
i
n
u
=
1
n
s
z
u
(
s
z
u
−
1
)
2
n(n-1)-\sum_{u=1,in_u=1}^{n}\cfrac{sz_u(sz_u-1)}{2}
n(n−1)−u=1,inu=1∑n2szu(szu−1)
代码:
#include<bits/stdc++.h>
#define pii pair<int,int>
#define int long long
#define cl(x,y) memset(x,y,sizeof(x))
#define loop(x,y,z) for(x=y;x<=z;x++)
#define reve(x,y,z) for(x=y;x>=z;x--)
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define lson x<<1,l,mid
#define rson x<<1|1,mid+1,r
#define INF 1e18
const int N=1e6+10;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
const double pi=acos(-1);
using namespace std;
vector<int> e[N];
int sz[N],in[N];
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--)
{
int n,i;
cin>>n;
loop(i,1,n)
{
e[i].clear();
sz[i]=1;
in[i]=0;
}
loop(i,1,n)
{
int u,v;
cin>>u>>v;
in[u]++;
in[v]++;
e[u].pb(v);
e[v].pb(u);
}
queue<int> q;
loop(i,1,n)
if(in[i]==1)
q.push(i);
while(!q.empty())
{
int u=q.front();
q.pop();
for(i=0;i<e[u].size();i++)
{
int v=e[u][i];
if(in[v]==1)
continue;
in[v]--;
if(in[v]==1)
q.push(v);
sz[v]+=sz[u];
}
}
int ans=n*(n-1);
loop(i,1,n)
if(in[i]==2)
ans-=sz[i]*(sz[i]-1)/2;
cout<<ans<<endl;
}
return 0;
}