zoukankan      html  css  js  c++  java
  • 【题解】luogu P3386 【模板】二分图匹配

    题面:https://www.luogu.org/problemnew/show/P3386

    好像没有人发Ford-Fulkerson,我来一发,
    这道题和P2756飞行员配对方案问题方法一样,网络流大法好。


    #include <bits/stdc++.h>
    using namespace std;
    const int inf=0x3f3f3f3f;
    const int Max=3000;
    struct node{
    	int to,cap,rev;
    };
    vector<node> v[Max];
    bool used[Max];
    int n,m,e;
    void add_node(int a,int b,int c) //加边
    {
    	v[a].push_back((node){b,c,v[b].size()});
    	v[b].push_back((node){a,0,v[a].size()-1});
    }
    int dfs(int s,int t,int f) //Ford—Fulkerson
    {
    	if(s==t) //源点和汇点相同,流量无限
    		return f;
    	used[s]=true;
    	for(int i=0;i<v[s].size();++i)
    	{
    		node &tmp=v[s][i]; //太长了。。。
    		if(used[tmp.to]==false&&tmp.cap>0)
    		{
    			int d=dfs(tmp.to,t,min(f,tmp.cap));
    			if(d>0) //添加反向边
    			{
    				tmp.cap-=d;
    				v[tmp.to][tmp.rev].cap+=d;
    				return d;
    			}
    		}
    	}
    	return 0;
    }
    int maxflow(int s,int t) //Ford-Fulkerson求网络最大流
    {
    	int flow=0;
    	while(1)
    	{
    		memset(used,false,sizeof(used));
    		int f=dfs(s,t,inf);
    		if(f==0)
    			return flow;
    		flow+=f;
    	}
    }
    int main()
    {
    	cin>>n>>m>>e;
    	for(int i=1;i<=n;++i) //建图
    		add_node(0,i,1);
    	for(int i=n+1;i<=n+m;++i)
    		add_node(i,n+m+1,1);
    	for(int i=1;i<=e;++i)
    	{
    		int a,b;
    		cin>>a>>b;
    		if(a<=n&&b<=m) //数据有毒,一定要加。
    		    add_node(a,n+b,1);//一定要加n;
    	}
    	cout<<maxflow(0,m+n+1)<<endl;
    	return 0;
    }
    
  • 相关阅读:
    fenby C语言 P32
    fenby C语言 P31 使用数组的指针
    fenby C语言 P30
    fenby C语言 P29
    fenby C语言 P28
    fenby C语言 P27使用指针
    fenby C语言 P25
    fenby C语言 P26
    fenby C语言P24
    Python学习之路:通过socket实现处理多个连接
  • 原文地址:https://www.cnblogs.com/yzhang-rp-inf/p/9432115.html
Copyright © 2011-2022 走看看