luogu P2057

Topic Link

The meaning of problems

There are n individuals, friends and m relationship, each person has a 01 mark, for everyone to reschedule 01 mark, it would have been different if a different tag, or a pair of friends of 01 marks, choose counted as a conflict, ask the least there will be several conflicts.

solution

Minimum cut, the first two opening points S, T respectively represent one original code is 0 or 1, and each connected to a corresponding node bidirectional side edges connected, and also connected edge between each pair of friends, attention here, because friendship is mutual. Meaning a cutting edge here is equivalent to a clash occurred.

#include<bits/stdc++.h>
using namespace std;
const int maxn=4e5+5;
inline int read(){
	char c=getchar();int t=0,f=1;
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){t=(t<<3)+(t<<1)+(c^48);c=getchar();}
	return t*f;
}
int n,m,s,t;
struct edge{
	int v,p,w;
}e[maxn<<1];
int h[maxn],cnt=1;
inline void add(int a,int b,int c){
	e[++cnt].p=h[a];
	e[cnt].v=b;
	e[cnt].w=c;
	h[a]=cnt;
}
const int inf=0x3f3f3f3f;
int dis[maxn];
bool bfs(){
	queue<int> q;
	memset(dis,0,sizeof(dis));
	dis[s]=1;
	q.push(s);
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=h[u];i;i=e[i].p){
			int v=e[i].v;
			if(e[i].w&&(dis[v]==0)){
				dis[v]=dis[u]+1;
				q.push(v);
			}
		}
	}
	return dis[t];
}
int ht[maxn];
int dfs(int u,int rest){
	if(rest==0||u==t){return rest;}
	int tot=0;
	for(int &i=ht[u];i;i=e[i].p){
		int v=e[i].v;
		if(e[i].w&&dis[v]==dis[u]+1){
			int di=dfs(v,min(e[i].w,rest));
			rest-=di;tot+=di;
			e[i].w-=di;e[i^1].w+=di;
			if(rest==0)break;
		}
	}
	return tot;
}
int dinic(){
	int ans=0;
	while(bfs()){
		int di=0;
		for(int i=1;i<=t;i++)ht[i]=h[i];
		while(di=dfs(s,inf))ans+=di;
	}
	return ans;
}
int main(){
	n=read(),m=read();
	s=n+1,t=n+2;
	for(int i=1;i<=n;i++){
		int a=read();
		if(a){
			add(s,i,1);
			add(i,s,0);
		}
		else{
			add(i,t,1);
			add(t,i,0);
		}
	}
	for(int i=1;i<=m;i++){
		int x=read(),y=read();
		add(x,y,1);
		add(y,x,1);
	}
	printf("%d\n",dinic());
	return 0;
}

Published 62 original articles · won praise 1 · views 1001

Guess you like

Origin blog.csdn.net/wmhtxdy/article/details/103796230