链接:点击打开链接
题意:求n个点m条边的有向无环图的最小路径覆盖
代码:
#include <queue>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
struct node{
int u,v,cap;
node(){}
node(int u,int v,int cap):u(u),v(v),cap(cap){}
}es[500005];
int R,S,T;
int dis[50005],iter[50005];
vector<int> tab[50005];
void addedge(int u, int v, int cap){
tab[u].push_back(R);
es[R++]=node(u,v,cap);
tab[v].push_back(R);
es[R++]=node(v,u,0);
}
int bfs(){
int i,h;
queue<int> q;
q.push(S);
memset(dis,INF,sizeof(dis));
dis[S]=0;
while(q.size()){
h=q.front();
q.pop();
for(i=0;i<tab[h].size();i++){
node &e=es[tab[h][i]];
if(e.cap>0&&dis[e.v]==INF){
dis[e.v]=dis[h]+1;
q.push(e.v);
}
}
}
return dis[T]<INF;
}
int dfs(int x,int maxflow){
int flow;
if(x==T)
return maxflow;
for(int &i=iter[x];i<tab[x].size();i++){
node &e=es[tab[x][i]];
if(dis[e.v]==dis[x]+1&&e.cap>0){
flow=dfs(e.v,min(maxflow,e.cap));
if(flow){
e.cap-=flow;
es[tab[x][i]^1].cap+=flow;
return flow;
}
}
}
return 0;
}
int dinic(){
int ans,flow;
ans=0;
while(bfs()){
memset(iter,0,sizeof(iter));
while(flow=dfs(S,INF))
ans+=flow;
}
return ans;
} //网络流求二分图最大匹配
int main(){
int i,j,k,x,y,n,m;
int s[505][505];
while(scanf("%d%d",&n,&m)!=EOF&&(n||m)){
R=0,S=0,T=2*n+1;
for(i=S;i<=T;i++)
tab[i].clear();
for(i=1;i<=n;i++)
addedge(S,i,1);
for(i=n+1;i<=2*n;i++)
addedge(i,T,1);
memset(s,0,sizeof(s));
for(i=0;i<m;i++){
scanf("%d%d",&x,&y);
s[x][y]=1; //拆点但是是只能从左连向右,可以找出一些情况证明不能从左连向右
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
s[i][j]=s[i][j]+s[i][k]*s[k][j]; //求传递闭包避免某些情况,例如
for(i=1;i<=n;i++) //http://www.cnblogs.com/ka200812/archive/2011/07/31/2122641.html
for(j=1;j<=n;j++)
if(s[i][j])
addedge(i,j+n,1);
printf("%d\n",n-dinic());
}
return 0;
}