网络流24题3 最小路径覆盖问题

题目

给定n个顶点m条边求这张图的最小路径覆盖。

题解

最小路径覆盖=总点数-最大匹配
在用网络流求自最大匹配。

代码

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#define min(x,y) x<y?x:y
#define max(x,y) x>y?x:y
const int maxf=0x7fffffff;
using namespace std;

struct arr{
    int y,w,next;
}a[1000001];
int n,m,nm,t,ans;
int ls[10001],q[10001],ha[10001],bo[10001],f[10001];

void add(int u,int v,int z){
    nm++; a[nm].y=v; a[nm].w=z; a[nm].next=ls[u]; ls[u]=nm;
    nm++; a[nm].y=u; a[nm].next=ls[v]; ls[v]=nm;
}

void init(){
    nm=1; int x,y;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++){
          scanf("%d %d",&x,&y);
          add(x,y+n,maxf);
    }
    for (int i=1;i<=n;++i)
        add(0,i,1);
    for (int i=1;i<=n;++i)
        add(i+n,8888,1);
}

bool bfs(){
    int x,t=0,w=1,p,i;
    memset(ha,-1,sizeof(ha));
    q[t]=ha[0]=0;
    while (t<w){
        x=q[t++];
        for (i=ls[x];i;i=a[i].next)
            if (a[i].w&&ha[a[i].y]<0){
                q[w++]=a[i].y;
                ha[a[i].y]=ha[x]+1;
            }
    }
    if (ha[8888]==-1) return 0;
    else return 1;
}

int dfs(int x,int maxf){
    if (x==8888) return maxf;
    int i=ls[x];
    int w,used=0;
    while(i){
        if(a[i].w&&ha[a[i].y]==ha[x]+1){
            w=maxf-used;
            w=dfs(a[i].y,min(w,a[i].w));
            if (w){
                f[x]=a[i].y;
                if (a[i].y-n>0) bo[a[i].y-n]=1;
            }
            a[i].w-=w;
            a[i^1].w+=w;
            used+=w;
            if(used==maxf)return maxf;
        }
        i=a[i].next;
    }
    if (used==0) ha[x]=-1;
    return used;
}

void code(){
    ans=n;
    while (bfs()) ans-=dfs(0,maxf);
    for(int i=1;i<=n;i++)
    {
        if (bo[i]) continue;
        printf("%d",i);
        int k=i;
        while (f[k]){
            printf(" %d",f[k]-n);
            k=f[k]-n;
        }
        printf("\n");
    }
    printf("%d",ans);
}

int main(){
    init();
    code();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值