AcWing 1183电力(Tarjan求割点)
题目链接:电力
题解:
使用
T
a
r
j
a
n
Tarjan
Tarjan求连通块时,如果某个点
x
x
x和他的儿子
t
m
p
tmp
tmp满足
d
f
n
[
x
]
≤
l
o
w
[
t
m
p
]
dfn[x]\leq low[tmp]
dfn[x]≤low[tmp]那么就说明点
x
x
x为割点,即经过
x
x
x进入
t
m
p
tmp
tmp后,无法在接下来的点中找到可以通往
x
x
x的路径,即如果删除点
x
x
x后,
t
m
p
tmp
tmp部分就回生成一个新的连通块,这样的话我们只需要跑
T
a
r
j
a
n
Tarjan
Tarjan求连通块个数,记为
c
t
ct
ct,然后在
T
a
r
j
a
n
Tarjan
Tarjan中记录下每个割点删除后最多能产生几个连通块(包括原来的那个连通块),取最大的为
a
n
s
ans
ans,最终答案就为
a
n
s
+
c
t
−
1
ans+ct-1
ans+ct−1。
注意:当割点为根节点(即除儿子们部分外就只有自己)时删除了这个点后会导致原来的那个连通块内点的数量变成0,即连通块数量要减去
1
。
1。
1。
细节和注释见代码:
vector<int>edge[N];
int dfn[N],low[N],vis[N],dfs_num;
void add(int u,int v){
edge[u].emplace_back(v);
edge[v].emplace_back(u);
}
int ans=0,root;
void tarjan(int x){//缩点染色求最多连通块
dfn[x]=++dfs_num;
low[x]=dfs_num;
vis[x]=1;
int res=0;
for(int i=0;i<edge[x].size();i++){
int tmp=edge[x][i];
if(!dfn[tmp]){
tarjan(tmp);
low[x]=min(low[x],low[tmp]);
if(dfn[x]<=low[tmp]){
res++;
}
}
else if(vis[tmp]){
low[x]=min(low[x],dfn[tmp]);
}
}
if(x!=root){
res++;
}
ans=max(ans,res);
}
int main(){
/*cout<<setiosflags(ios::fixed)<<setprecision(8)<<ans<<endl;//输出ans(float)格式控制为8位小数(不含整数部分)*/
/*cout<<setprecision(8)<<ans<<endl;//输出ans(float)格式控制为8位小数(含整数部分)*/
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);//同步流
int n,m;
while(cin>>n>>m&&n+m){
dfs_num=0;
for(int i=1;i<=n;i++){
edge[i].clear();
dfn[i]=low[i]=vis[i]=0;
}
for(int i=1;i<=m;i++){
int u,v;
cin>>u>>v;
u++;
v++;
add(u,v);
}
ans=0;
int ct=0;//初始连通块数量
for(int i=1;i<=n;i++){
if(!vis[i]){
root=i;
tarjan(i);
ct++;
}
}
cout<<ct+ans-1<<endl;
}
return 0;
}