萌新dinic求调
查看原帖
萌新dinic求调
494601
gcx12012楼主2023/1/25 12:16
#include<bits/stdc++.h>
#include<cmath>
#define ll long long

using namespace std;
const ll inf=1e9;
struct node{
	int to,val,nxt;
}e[1000010];
int head[1000010],h[1000010];
int m,n,u,v,cnt=0,tot=0,S,T;

ll read(){
	ll x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
void add(ll u,ll v,ll w){
	e[++cnt].to=v;
	e[cnt].val=w;
	e[cnt].nxt=head[u];
	head[u]=cnt;
	e[++cnt].to=u;
	e[cnt].val=0;
	e[cnt].nxt=head[v];
	head[v]=cnt;
}
int bfs(){
	memset(h,-1,sizeof(h));
	h[S]=0;
	queue<int >q;
	q.push(S);
	while(!q.empty()){
		int u=q.front();
		q.pop();
		for(int i=head[u];i;i=e[i].nxt){
			int v=e[i].to;
			if(h[v]==-1 && e[i].val){
				h[v]=h[u]+1;
				q.push(v);
			}
		}
	}
	return (h[T]==-1?0:1);
}
int dfs(int x,int f){
	if(x==T) return f;
    int w,used=0;
    for(int i=head[x];i;i=e[i].nxt){
        int v=e[i].to;
        if(h[v]==h[x]+1 && e[i].val){
            w=dfs(v,min(f-used,e[i].val));
            e[i].val-=w;
            e[i^1].val+=w;
            used+=w;
            if(used==f) return f;
        }
    }
    if(!used) h[x]=-1;
    return used;
}
void dinic(){
	while(bfs()){
		tot+=dfs(S,inf);
	}
}

int main()
{
	m=read(),n=read();
	u=read(),v=read();
	S=0,T=n+1;
	do{
		add(u,v,inf);
		u=read(),v=read();
	}while(u!=-1 && v!=-1);
	for(int i=1;i<=m;i++) add(S,i,1);
	for(int i=m+1;i<=n;i++) add(i,T,1);
	dinic();
	if(!tot){
		cout<<"No Solution!"<<endl;
		return 0;
	}
	cout<<tot<<endl;
	for(int i=2;i<=cnt;i+=2){
		if(e[i].to!=S && e[i^1].to!=S && e[i].to!=T && e[i^1].to!=T && e[i^1].val) cout<<e[i^1].to<<' '<<e[i].to<<endl;
	}
	return 0;
}
2023/1/25 12:16
加载中...