题目来源:https://www.luogu.org/problem/show?pid=3469#sub
判断割点的算法详见博客:http://blog.csdn.net/moon_sky1999/article/details/78169738
WA了几次,要注意数据可能较大,要用long long。
题目可以这么理解:
节点cur所要求的ans值,即为将节点cur摘出来,作为一个联通块,然后再求所有联通块间的点对的个数。
这样如果cur不是割点,那么图中被分成两个联通块,其中一个节点数为1,另一个节点数为n-1,这样此时cur的ans值为2*(n-1)。
如果cur是割点,计tot为目前已访问到的联通块中的节点总数,这样每找到一个联通块,ans值应+tot*2*num[x],其中num[x]是x所在的联通块的节点个数。
判断cur是否为割点的条件,同样是判断去除节点cur后,其dfs子树是否是一新的联通块的条件。
要注意计算完子树,后还有节点cur的父节点所在的联通块,其节点个数为n-tot。ans值要在最后加上(n-tot)*tot*2。
处理dfs子树思路与此博客中的思路类似:http://blog.csdn.net/moon_sky1999/article/details/78169939
具体细节详见代码:
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn=1e5+10;
long long n,m;
struct data{int next,to;}e[maxn*7];
int head[maxn];
int cnt=0;
void ins(int u,int v)
{
e[++cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt;
}
int dfn[maxn];
long long ans[maxn];
int low[maxn];
long long num[maxn];
bool cut[maxn];
int vis[maxn];
void cut_bridge(int cur,int fa,int dep)
{
vis[cur]=1;
dfn[cur]=low[cur]=dep;
int children=0;
num[cur]++;
long long tot=1;
for(int i=head[cur];i;i=e[i].next)
{
int x=e[i].to;
if(vis[x]==1&&x!=fa)
{
if(dfn[x]<low[cur])low[cur]=dfn[x];
}
if(vis[x]==0)
{
cut_bridge(x,cur,dep+1);
children++;
num[cur]+=num[x];
if(low[x]<low[cur])low[cur]=low[x];
if((fa==-1&&children>1)||(fa!=-1&&low[x]>=dfn[cur]))
{
cut[cur]=1;
ans[cur]+=num[x]*tot*2;
tot+=num[x];
}
}
}
if(cut[cur])ans[cur]+=(n-tot)*tot*2;
else ans[cur]=(n-1)*2;
vis[cur]=2;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
ins(x,y);ins(y,x);
}
cut_bridge(1,-1,0);
for(int i=1;i<=n;i++)cout<<ans[i]<<endl;
return 0;
}