易水人去,明月如霜。
Description
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
1 2
2 3
1 3
3 4
4 5
Sample Output
8
8
16
14
8
思路:
8
16
14
8
这一题中蕴含的技巧就是求割点时计算其将图分成了多少个大小为多少的连通块。
因为答案就是这些连通块大小互相乘的和。
关键在于,再求割点时维护一个vis[i]代表搜索树中这个子树的大小。
因为一个割点将图分成的连通块是其下面的所有子树(互不相连)与这个点上面的所有点。tmp表示这个点的子树之前的同父亲子树的和。为什么这么算可以得到答案,可以自己推一推。
不要忘记最后答案要乘2。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#define pa pair<int,int>
#define inf 1000000000
#define ll long long
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m,cnt,ind;
int last[100005],size[100005],dfn[100005],low[100005];
ll ans[100005];
struct edge{int to,next;}e[1000005];
void insert(int u,int v)
{
e[++cnt].to=v;e[cnt].next=last[u];last[u]=cnt;
e[++cnt].to=u;e[cnt].next=last[v];last[v]=cnt;
}
void tarjan(int x)
{
int t=0;
size[x]=1;
dfn[x]=low[x]=++ind;
for(int i=last[x];i;i=e[i].next)
if(dfn[e[i].to])low[x]=min(low[x],dfn[e[i].to]);
else
{
tarjan(e[i].to);
size[x]+=size[e[i].to];
low[x]=min(low[x],low[e[i].to]);
if(dfn[x]<=low[e[i].to])
{
ans[x]+=(ll)t*size[e[i].to];
t+=size[e[i].to];
}
}
ans[x]+=(ll)t*(n-t-1);
}
int main()
{
n=read();m=read();
for(int i=1;i<=m;i++)
{
int u=read(),v=read();
insert(u,v);
}
tarjan(1);
for(int i=1;i<=n;i++)
printf("%lld\n",(ans[i]+n-1)*2);
return 0;
}