萌新第一次做网络流,不知道问题所在
查看原帖
萌新第一次做网络流,不知道问题所在
701408
lao_wang楼主2024/9/5 11:28
#include<bits/stdc++.h>
#define inf 2147483647
#define N 112345
#define int long long
using namespace std ;
int n , m , head[N] , dep[N] , cnt=0 , s , t , now[N] ;
bool f[N] ;
vector<int> road[N] ;
struct node{
	int to , w , next ;
}e[N<<2];
void use(int u,int v,int w){
	e[cnt].to = v ;
	e[cnt].next = head[u] ;
	e[cnt].w = w ;
	head[u] = cnt++ ;
}
void newnet(int u,int v,int w){
	use(u,v,w) ;
	use(v,u,0) ;
}
bool bfs(){
	for(int i=1;i<=t;i++) dep[i]=inf , f[i]=0 , now[i]=head[i] ;
	queue<int> q ;
	dep[s] = 0 ;
	q.push(s) ;
	while(!q.empty()){
		int u=q.front() ;
		q.pop() ;
		f[u]=0 ;
		for(int i=head[u];~i;i=e[i].next){
			int x=e[i].to ;
			if(dep[u]+1<dep[x]&&e[i].w){
				dep[x] = dep[u]+1 ;
				if(!f[x]){
					f[x]=1 ;
					q.push(x) ;
				}
			}
		}
	}
	return dep[t]!=inf ;
}
int dfs(int u,int sum){
	if(u==t) return sum ;
	int use=0 ;
	for(int i=now[u];~i;i=e[i].next){
		now[u] = i ;
		int x=e[i].to ;
		if(dep[u]+1!=dep[x]||!e[i].w) continue ;
		int temp=dfs(x,min(e[i].w,sum)) ;
		if(!temp) continue ;
		e[i].w -= temp ;
		e[i^1].w += temp ;
		use += temp ;
		sum -= temp ;
		if(!sum) break ;
	}
	return use ;
}
void dinic(){
	int ans=0 ;
	while(bfs()) ans += dfs(s,inf) ;
	cout << n-ans ;
}
void plant(int u,bool col){
	f[u]=1 ;
	if(!col) newnet(s,u,1) ;
	else newnet(u,t,1) ;
	for(auto x:road[u]){
		if(f[x]) continue ;
		if(!col) newnet(u,x,1) ;
		plant(x,!col) ;
	}
}
signed main(){
	memset(head,-1,sizeof head) ;
	cin >> n >> m ;
	s = n+1 ; t = s+1 ;
	for(int i=1;i<=m;i++){
		int x , y ;
		scanf("%lld%lld",&x,&y) ;
		road[x].push_back(y) ;
		road[y].push_back(x) ;
	}
	for(int i=1;i<=n;i++) if(!f[i]) plant(i,0) ;
	dinic() ;
	return 0 ;
}
2024/9/5 11:28
加载中...