1 条题解

  • 0
    @ 2023-6-21 19:57:31

    C++ :

    #include <algorithm>
    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>
    using namespace std;
    const int inf=1e9+10;
    const int maxn=5e2+10;
    const int maxm=1e5+10;
    namespace Dinic
    {
    	struct edge{int to,cap,flow,last;}line[maxm];
    	int n,s,t,pos=1,head[maxn],que[maxn],dis[maxn],vis[maxn],cur[maxn];
    	
    	void Init(int _n,int _s,int _t){n=_n; s=_s; t=_t;}
    	void AddEdge(int from,int to,int cap)
    	{
    		line[++pos]=(edge){to,cap,0,head[from]}; head[from]=pos;
    		line[++pos]=(edge){from,0,0,head[to]}; head[to]=pos;
    	}
    	bool BFS()
    	{
    		for(int i=1;i<=n;++i)vis[i]=false;
    		int lead=0,tail=1; que[tail]=s; vis[s]=true; 
    		while(lead<tail)
    		{
    			int u=que[++lead];
    			for(int i=head[u];i;i=line[i].last)
    			{
    				edge e=line[i];
    				if(!vis[e.to] && e.cap>e.flow)
    				{
    					vis[e.to]=true;
    					que[++tail]=e.to;
    					dis[e.to]=dis[u]+1;
    				}
    			}
    		}
    		return vis[t];
    	}
    	int DFS(int u,int a)
    	{
    		if(u==t || a==0)return a;
    		int flow=0,f;
    		for(int &i=cur[u];i;i=line[i].last)
    		{
    			edge &e=line[i];
    			if(dis[e.to]==dis[u]+1 && (f=DFS(e.to,min(a,e.cap-e.flow)))>0)
    			{
    				e.flow+=f; line[i^1].flow-=f;
    				flow+=f; a-=f; if(a==0)break;
    			}
    		}
    		return flow;
    	}
    	int Maxflow()
    	{
    		int flow=0;
    		while(BFS())
    		{
    			for(int i=1;i<=n;++i)cur[i]=head[i];
    			flow+=DFS(s,inf);
    		}
    		return flow;
    	}
    	void Solve(int m,int *fa,int *son)
    	{
    		for(int u=1;u<=m;++u)
    			for(int i=head[u];i;i=line[i].last)
    				if(line[i].flow==1)fa[line[i].to-m]=u,son[u]=line[i].to-m;
    	}
    }
    int n,m,s,t,fa[maxn],son[maxn];
    void init()
    {
    	scanf("%d%d",&n,&m); s=n+n+1; t=n+n+2; int a,b;
    	for(int i=1;i<=n;++i)Dinic :: AddEdge(s,i,1);
    	for(int i=1;i<=n;++i)Dinic :: AddEdge(i+n,t,1);
    	for(int i=1;i<=m;++i)
    	{
    		scanf("%d%d",&a,&b);
    		Dinic :: AddEdge(a,b+n,1);
    	}
    	Dinic :: Init(n+n+2,s,t);
    }
    void solve()
    {
    	int ans=n-Dinic :: Maxflow();
    	Dinic :: Solve(n,fa,son);
    	for(int i=1;i<=n;++i)if(!fa[i])
    	{
    		int t=i;
    		while(t)printf("%d ",t),t=son[t];
    		printf("\n");
    	}
    	printf("%d\n",ans);
    }
    int main()
    {
    	init();
    	solve();
    	return 0;
    }
    
    
    • 1

    #6002. 「网络流 24 题」最小路径覆盖

    信息

    ID
    992
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者