[网络流24题] 最小路径覆盖问题
题目链接:戳我
感觉很套路了,就不多说了,直接上代码了。。。。
代码如下
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define MAXN 100010
#define S 0
#define T n*2+1
using namespace std;
int n,t=1,ans,m;
int head[MAXN],dis[MAXN],cur[MAXN],to[MAXN],done[MAXN];
bool issqr[MAXN*10];
struct Edge{int nxt,to,dis;}edge[MAXN];
inline void add(int from,int to,int dis)
{
edge[++t].nxt=head[from],edge[t].to=to,edge[t].dis=dis,head[from]=t;
edge[++t].nxt=head[to],edge[t].to=from,edge[t].dis=0,head[to]=t;
}
inline bool bfs()
{
queue<int>q;
memset(dis,0x3f,sizeof(dis));
memcpy(cur,head,sizeof(head));
q.push(S);dis[S]=0;
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i;i=edge[i].nxt)
{
int v=edge[i].to;
if(dis[v]==0x3f3f3f3f&&edge[i].dis)
dis[v]=dis[u]+1,q.push(v);
}
}
if(dis[T]==0x3f3f3f3f) return false;
return true;
}
inline int dfs(int x,int f)
{
if(!f||x==T) return f;
int used=0,w;
for(int i=cur[x];i;i=edge[i].nxt)
{
int v=edge[i].to;
cur[x]=i;
if(dis[v]==dis[x]+1&&(w=dfs(v,min(edge[i].dis,f))))
{
used+=w,f-=w;
edge[i].dis-=w,edge[i^1].dis+=w;
to[x]=v;
if(!f) break;
}
}
return used;
}
inline int dinic()
{
int cur_ans=0;
while(bfs()) cur_ans+=dfs(S,(int)1e9);
return cur_ans;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ce.in","r",stdin);
#endif
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v+n,1);
}
for(int i=1;i<=n;i++) add(S,i,1),add(i+n,T,1);
ans=dinic();
to[0]=0;
for(int i=1;i<=ans;i++)
{
if(done[i]==1) continue;
printf("%d ",i);done[i]=1;
int now=to[i]>ans?to[i]-n:to[i]; done[now]=1;
while(now!=0)
{
printf("%d ",now);
now=to[now]>ans?to[now]-n:to[now];done[now]=1;
}
printf("\n");
}
printf("%d\n",n-ans);
return 0;
}