标签:cin code cpp ini class add return cap pac
#include <bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int MAXN=10000;
const int MAXM=100000;
struct Edge
{
int to,nxt,cap,flow;
}edge[MAXM];
int head[MAXN],tot,dis[MAXN],S,T,n,m;
void init()
{
memset(head,-1,sizeof(head));
tot=0;
}
void addedge(int u,int v,int cap)
{
edge[tot].to=v; edge[tot].cap=cap; edge[tot].flow=0;
edge[tot].nxt=head[u]; head[u]=tot++;
edge[tot].to=u; edge[tot].cap=0; edge[tot].flow=0;
edge[tot].nxt=head[v]; head[v]=tot++;
}
queue<int>q;
bool bfs()
{
memset(dis,0,sizeof(dis));
while(!q.empty()) q.pop();
q.push(S);
dis[S]=1;
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
int v=edge[i].to;
if(!dis[v]&&edge[i].cap>edge[i].flow)
{
dis[v]=dis[u]+1;
q.push(v);
}
}
}
return dis[T];
}
int dfs(int u,int f)
{
if(u==T) return f;
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
int v=edge[i].to;
if(dis[u]+1==dis[v]&&edge[i].cap>edge[i].flow)
{
int f1=dfs(v,min(f,edge[i].cap-edge[i].flow));
if(f1)
{
edge[i].flow+=f1;
edge[i^1].flow-=f1;
return f1;
}
}
}
return 0;
}
int dinic()
{
int ans=0;
while(bfs()) ans+=dfs(S,inf);
return ans;
}
int to[MAXN];
bool vis[MAXN];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>m;
init();
S=0;
T=2*n+1;
int u,v;
for(int i=1;i<=m;i++)
{
cin>>u>>v;
addedge(u,v+n,1);
}
for(int i=1;i<=n;i++)
{
addedge(S,i,1);
addedge(i+n,T,1);
}
int ans=n-dinic();
for(int i=1;i<=n;i++)
{
for(int j=head[i];j!=-1;j=edge[j].nxt)
{
if(edge[j].flow==1)
{
to[i]=edge[j].to-n;
break;
}
}
}
for(int i=1;i<=n;i++)
{
int flag=0;
if(!vis[i])
{
while(i)
{
vis[i]=1;
if(flag) cout<<" ";
flag=1;
cout<<i;
i=to[i];
}
cout<<endl;
}
}
cout<<ans<<endl;
return 0;
}
标签:cin code cpp ini class add return cap pac
原文地址:https://www.cnblogs.com/scott527407973/p/11216017.html