https://www.luogu.org/problemnew/show/P2764
DAG的最小路径覆盖知识点:https://www.cnblogs.com/justPassBy/p/5369930.html
#include <bits/stdc++.h>
using namespace std;
const int maxn=305;
const int INF=0x3f3f3f3f;
struct Edge{
int from,to,cap,flow;
};
struct Dinic{
int n,m0,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init()
{
char str[10000];
int tool,len;
cin>>n>>m0;
s=0;t=n*2+1;
int a,b;
for(int i=1;i<=m0;i++)
{
scanf("%d%d",&a,&b);
AddEdge(a,n+b,1);
}
for(int i=1;i<=n;i++)AddEdge(s,i,1);
for(int i=n+1;i<=n*2;i++)AddEdge(i,t,1);
}
void AddEdge(int f,int t,int c)
{
edges.push_back((Edge){f,t,c,0});
edges.push_back((Edge){t,f,0,0});
m=edges.size();
G[f].push_back(m-2);
G[t].push_back(m-1);
}
bool bfs()
{
memset(vis,0,sizeof(vis));
queue<int> Q;
Q.push(s);
d[s]=0;
vis[s]=1;
while(!Q.empty())
{
int x=Q.front();Q.pop();
for(int i=0;i<G[x].size();i++)
{
Edge& e=edges[G[x][i]];
if(!vis[e.to] && e.cap>e.flow)
{
vis[e.to]=1;
d[e.to]=d[x]+1;
Q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int x,int a)
{
if(x==t || a==0)return a;
int flow=0,f;
for(int& i=cur[x];i<G[x].size();i++)
{
Edge& e=edges[G[x][i]];
if(d[x]+1==d[e.to] && (f=dfs(e.to,min(a,e.cap-e.flow)))>0)
{
e.flow+=f;
edges[G[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(!a)break;
}
}
return flow;
}
int MaxFlow()
{
int flow=0;
while(bfs())
{
memset(cur,0,sizeof(cur));
flow+=dfs(s,INF);
}
return flow;
}
void print(int flow)
{
int last[155]={0},nxt[155]={0};
for(int i=0;i<m0*2;i+=2)
{
int from=edges[i].from,to=edges[i].to;
if(edges[i].flow==1)
{
nxt[from]=to-n;
last[to-n]=from;
}
}
for(int i=1;i<=n;i++)if(last[i]==0)
{
int u=i;
while(u)
{
printf("%d ",u);
u=nxt[u];
}
putchar('\n');
}
printf("%d\n",n-flow);
}
}ans;
int main()
{
//freopen("input.in","r",stdin);
ans.init();
int flow=ans.MaxFlow();
ans.print(flow);
return 0;
}