Subject to the effect:
Topic links: https://www.luogu.org/problemnew/show/P2764
Given a directed graph . Assume is set a simple passage (vertex disjoint) a. in case Each point just of a road, called is a path covered. path from a start point of any length is arbitrary, in particular, may be 。 minimum path is covered minimum number of paths contained in the path covered by a design of an efficient algorithm for (directed acyclic graph) minimum path coverage.
Ideas:
As the title requires any point have to go just once, so it is certainly to be demolished points, each point is split into the
.
for
in each side
, we built side
, flow rate 1. This limits each side can only go once.
It is then connected to a source
,
is connected to the sink, the maximum running flow, we get最多可以合并几条道路
. Because the flow once the merger is equivalent to a road.
So is the minimum path cover
the maximum flow.
Scheme may be utilized, then output the residual flow, the recursive program output.
Code:
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=100010,Inf=1e9;
int n,m,S,T,tot=1,maxflow,head[N],dep[N],cur[N];
bool vis[N];
struct edge
{
int from,to,flow,next;
}e[N];
void add(int from,int to,int flow)
{
e[++tot].to=to;
e[tot].flow=flow;
e[tot].next=head[from];
head[from]=tot;
}
bool bfs()
{
memcpy(cur,head,sizeof(cur));
memset(dep,0x3f3f3f3f,sizeof(dep));
queue<int> q;
q.push(S);
dep[S]=1;
while (q.size())
{
int u=q.front(),v;
q.pop();
for (int i=head[u];~i;i=e[i].next)
{
v=e[i].to;
if (dep[v]>dep[u]+1&&e[i].flow)
{
dep[v]=dep[u]+1;
q.push(v);
}
}
}
return dep[T]<Inf;
}
int dfs(int x,int flow)
{
int low=0;
if (x==T)
{
maxflow+=flow;
return flow;
}
int used=0;
for (int i=cur[x];~i;i=e[i].next)
{
int y=e[i].to;
cur[x]=i;
if (dep[y]==dep[x]+1&&e[i].flow)
{
low=dfs(y,min(e[i].flow,flow-used));
if (low)
{
used+=low;
e[i].flow-=low;
e[i^1].flow+=low;
if (used==flow) break;
}
}
}
return used;
}
void dinic()
{
while (bfs())
dfs(S,Inf);
}
void find(int x)
{
vis[x-n]=1;
printf("%d ",x-n);
for (int i=head[x];~i;i=e[i].next)
{
int y=e[i].to;
if (!e[i].flow && y!=x-n && !vis[y])
{
find(y+n);
return;
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x+n,y,1);
add(y,x+n,0);
}
S=N-1; T=N-2;
for (int i=1;i<=n;i++)
{
add(S,i+n,1);
add(i+n,S,0);
add(i,T,1);
add(T,i,0);
}
dinic();
vis[S]=vis[T]=1;
for (int i=1;i<=n;i++)
if (!vis[i])
{
find(i+n);
putchar(10);
}
printf("%d\n",n-maxflow);
return 0;
}