https://www.lydsy.com/JudgeOnline/problem.php?id=1123
Byteotia城市有n个 towns m条双向roads. 每条 road 连接 两个不同的 towns ,没有重复的road. 所有towns连通。
Input
输入n<=100000 m<=500000及m条边
Output
输出n个数,代表如果把第i个点去掉,将有多少对点不能互通。
Sample Input
5 5
1 2
2 3
1 3
3 4
4 5
Sample Output
8
8
16
14
8
Hint
思路:根据割点的定义,若节点 i i i不是割点,那么把节点 i i i关联的边都去掉之后,只有 i i i与其他 n − 1 n-1 n−1个点不连通,因此答案为 2 ∗ ( n − 1 ) 2*(n-1) 2∗(n−1);若节点 i i i为割点,那么去掉与节点 i i i关联的边后,会把图分成几个连通块,我们应该分别求得这些连通块的大小,再计算答案。不妨设节点 i i i的子节点集合中,有 t t t个点 s 1 , s 2 … … s t s_{1},s_{2}……s_{t} s1,s2……st满足割点判定法则 d f n [ i ] < = l o w [ s k ] dfn[i]<=low[s_{k}] dfn[i]<=low[sk],那么删除与节点 i i i关联的边后,无向图至多分成 t + 2 t+2 t+2个连通块:(1)节点 i i i自身单独成一个连通块。(2)有 t t t个连通块,分别由搜索树上以 s k s_{k} sk为根的子树中的节点构成。(3)还可能有一个连通块由剩下的点构成。如图:
设
s
i
z
[
x
]
siz[x]
siz[x]表示以
x
x
x为根的子树的大小,那么删掉一个割点
i
i
i的贡献为:
∑
k
=
1
t
s
i
z
[
s
k
]
∗
(
n
−
s
i
z
[
s
k
]
)
+
1
∗
(
n
−
1
)
+
(
n
−
1
−
s
u
m
)
∗
(
1
+
s
u
m
)
\sum_{k=1}^{t}siz[s_{k}]*(n-siz[s_{k}])+1*(n-1)+(n-1-sum)*(1+sum)
k=1∑tsiz[sk]∗(n−siz[sk])+1∗(n−1)+(n−1−sum)∗(1+sum)
其
中
s
u
m
=
∑
k
=
1
t
s
i
z
[
s
k
]
其中sum=\sum_{k=1}^{t}siz[s_{k}]
其中sum=k=1∑tsiz[sk]
这些都是可以在
t
a
r
j
a
n
tarjan
tarjan的
d
f
s
dfs
dfs过程中维护的。
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
const int maxm=5e5+5;
struct edge
{
int to,nxt;
}Edge[maxm<<1];
bool cut[maxn];
int head[maxn],dfn[maxn],low[maxn],siz[maxn];
ll ans[maxn];
int n,m,tot,num,root;
inline void addedge(int x,int y)
{
Edge[++tot].to=y,Edge[tot].nxt=head[x],head[x]=tot;
}
void tarjan(int x)
{
int y,flag=0,sum=0;
dfn[x]=low[x]=++num;
siz[x]=1;
for(int i=head[x];i;i=Edge[i].nxt)
{
y=Edge[i].to;
if(!dfn[y])//未访问过的节点
{
tarjan(y);
siz[x]+=siz[y];
low[x]=min(low[x],low[y]);
if(low[y]>=dfn[x]) //桥
{
++flag;
ans[x]+=ll(siz[y])*(n-siz[y]);
sum+=siz[y];
if(x!=root||flag>=2)
cut[x]=1;
}
}
else
low[x]=min(low[x],dfn[y]);
}
if(cut[x])
ans[x]+=n-1+ll(n-1-sum)*(1+sum);
else
ans[x]=2*(n-1);
}
int main()
{
scanf("%d%d",&n,&m);
int x,y;
tot=1;
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
addedge(x,y),addedge(y,x);
}
root=1;
tarjan(1);
for(int i=1;i<=n;i++)
printf("%lld\n",ans[i]);
return 0;
}