小白月赛12 I华华和月月逛公园(tarjan求桥)

题目链接

题意:给你n个点,m条边,求有多少条边是不一定要经过的。

题解:tarjan求桥模板题,如果这条边是桥,那么是一定要经过的。

判断桥的条件:low[v]>dfn[u],这样说明low[v]没有被更新,也就不存在环了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+100;
struct edge{
	int next,v;
}e[maxn*6];
int head[maxn],low[maxn],dfn[maxn];
int cnt,tot,res;
void insert(int u,int v){
	e[++tot].next=head[u];e[tot].v=v;head[u]=tot;
	e[++tot].next=head[v];e[tot].v=u;head[v]=tot;
}
void tarjan(int u,int fa){
	low[u]=dfn[u]=++cnt;
	for(int i=head[u];i;i=e[i].next){
		int v = e[i].v;
		if(v==fa) continue;
		if(!dfn[v]) {
			tarjan(v,u);
			low[u]=min(low[u],low[v]);
			if(low[v]>dfn[u]) res++;
		}
		else low[u] = min(low[u],dfn[v]);
	} 
}
int main()
{
	int n,m,u,v;
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		cin>>u>>v;
		insert(u,v);
	}
	tarjan(1,0);
	printf("%d\n",m-res);
 } 

猜你喜欢

转载自blog.csdn.net/qq_42129242/article/details/91041197