P2764 最小路径覆盖问题
有向无环图的最小路径覆盖=点数-二分图最大匹配数
由于之前写二分图最大匹配已经写的很多了,这次换做最大流的做法做一遍
建图:这题的建图也很简单,的每一个点都构造一个复制,编号为,左右各一个超级源点,编号为0和,边的容量为1
至于输出路径,一开始想了好久,发现怎么都不对,原来是没有把dinic写在前面,所以相当于一直在假的网络流上跑
一个next数组记录下每一个点的下一个点,并记录下哪些是深度为0的,从这些深度为0的开始遍历
代码:
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=2e6+7;
const int maxm=2e6+7;
const int INF=1e9;
const ll INFF=1e18;
struct Edge
{
int to,next,cap,flow;
}edge[maxm];
int tol,head[maxn];
void init()
{
tol=2;
mem(head,-1);
}
void add(int u,int v,int w,int rw=0)
{
edge[tol].to=v;edge[tol].cap=w;edge[tol].flow=0;
edge[tol].next=head[u];head[u]=tol++;
edge[tol].to=u;edge[tol].cap=rw;edge[tol].flow=0;
edge[tol].next=head[v];head[v]=tol++;
}
int Q[maxn],dep[maxn],cur[maxn],sta[maxn],n,m,a,b,D[maxn],next[maxn];
bool bfs(int sx,int ex)
{
int front=0,tail=0;
mem(dep,-1);
dep[sx]=0;
Q[tail++]=sx;
while(front<tail)
{
int u=Q[front++];
for (int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if (edge[i].cap>edge[i].flow&&dep[v]==-1)
{
dep[v]=dep[u]+1;
if (v==ex)return true;
Q[tail++]=v;
}
}
}
return false;
}
int dinic(int sx,int ex,int n)
{
int maxflow=0;
while(bfs(sx,ex))
{
rep(i,0,2*n+1)cur[i]=head[i];
int u=sx,tail=0;
while(cur[sx]!=-1)
{
if (u==ex)
{
int tp=INF;
for (int i=tail-1;i>=0;i--)
{
tp=min(tp,edge[sta[i]].cap-edge[sta[i]].flow);
}
maxflow+=tp;
for (int i=tail-1;i>=0;i--)
{
edge[sta[i]].flow+=tp;
edge[sta[i]^1].flow-=tp;
if (edge[sta[i]].cap-edge[sta[i]].flow==0)tail=i;
}
u=edge[sta[tail]^1].to;
}
else if (cur[u]!=-1&&edge[cur[u]].cap>edge[cur[u]].flow&&dep[u]+1==dep[edge[cur[u]].to])
{
sta[tail++]=cur[u];
u=edge[cur[u]].to;
}
else
{
while(u!=sx&&cur[u]==-1)
{
u=edge[sta[--tail]^1].to;
}
cur[u]=edge[cur[u]].next;
}
}
}
return maxflow;
}
int main()
{
init();
scanf("%d%d",&n,&m);
rep(i,1,m)
{
scanf("%d%d",&a,&b);
add(a,b+n,1,0);
}
rep(i,1,n)
{
add(0,i,1,0);
add(i+n,2*n+1,1,0);
}
int ans=dinic(0,2*n+1,n);
rep(u,1,n)
{
for (int i=head[u];i!=-1;i=edge[i].next)
{
int to=edge[i].to,flow=edge[i^1].flow;
if (to>n&&flow)
{
D[to-n]++;
next[u]=to-n;
}
}
}
rep(u,1,n)
{
if (!D[u])
{
printf("%d ",u);
for (int i=next[u];i!=0;i=next[i])printf("%d ",i);
printf("\n");
}
}
W(n-ans);
}
来源:CSDN
作者:w_udixixi
链接:https://blog.csdn.net/w_udixixi/article/details/104459504