好奇为什么我要特判才能过
查看原帖
好奇为什么我要特判才能过
836262
ZZK423楼主2023/6/27 15:30
#include<bits/stdc++.h>
#define int long long
using namespace std;

int n,m;
struct edge{
	int a,b;
};
//存储图中所有的桥 
vector<edge> e;
//邻接矩阵存图 
vector<int> g[100010];
//节点i 在图中的搜索次序 
int dfn[100010];
//节点i 可回溯到最早位于栈中的节点 
int low[100010];
//时间戳 
int timestamp;
int deg[100010];
//DCC_Module
int dcc_id[10010],dcc_size[10010], dcc_cnt;
stack<int> st;
//题目输出顺序要求 
bool cmp(edge a,edge b) {
    if(a.a==b.a){
    	return a.b<b.b;
    }
    return a.a<b.a;
}

void tarjan(int to,int from){
	timestamp++;
	dfn[to] = low[to] = timestamp;
	st.push(to);
	for(int i=0;i<g[to].size();i++){
		int j = g[to][i];
		if(j == from)continue;
		if(!dfn[j]){
			tarjan(j,to);
			low[to] = min(low[to],low[j]); 
			//发现割边 
			if(low[j]>dfn[to]){
				//cout<<to<<endl;
				e.push_back({to,j});
			}
		}else{
			low[to] = min(low[to],dfn[j]); 
		}
	} 
	if(low[to] == dfn[to]){
		int j;
		dcc_cnt++;
		while(j!=to){
			j = st.top();
			st.pop();
			dcc_id[j] = dcc_cnt;
			dcc_size[dcc_cnt]++;
		}
		
	} 
}
signed main(){
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int x,y;
		cin>>x>>y;
		g[x].push_back(y);
		g[y].push_back(x);
	}

	tarjan(1,-1);
	for(int i=0;i<e.size();i++){
		int a = e[i].a;
	//	cout<<a<<endl;
		int b = e[i].b;
	//	cout<<b<<endl;
		deg[dcc_id[a]]++;
		deg[dcc_id[b]]++;
	} 

	int ans = 0;
	//遍历图中的所有双连通分量 
	for(int i=1;i<=dcc_cnt;i++){
		ans += (deg[i] == 1); 
	} 
	if((ans+1)/2 == 1){
		cout<<0<<endl;
		return 0;
	}
	cout<<(ans+1)/2<<endl;
	
}
2023/6/27 15:30
加载中...