P2764 最小路径覆盖问题

· · 个人记录

P2764 最小路径覆盖问题

最小路径覆盖换句话说是用一些边把点合并起来,然后去找合并后的最小集合数了。

1.拆点为A、B,表示未被合并的一个点,从源点向A连边,边权为1,B向汇点连边,边权为1,连边和魔术球问题比较相似,可以想一想。

2.对于一条(x -> y)的边,A[x] -> B[y]连边,边权为1,如此最大流可能加1,表示这个边被选中合并两个端点

3.方案的话就记一下前驱和后继就可以

代码如下

#include<bits/stdc++.h>
using namespace std;
const int maxn = 202020;
const int inf = 1e9;
int n,m,str,end,tot = -1,ans;
int head[maxn],deep[maxn],net[maxn],pre[maxn];
struct node
{
    int to,net,va;
}data[maxn<<1];

void add(int x,int y,int va)
{
    data[++tot].net = head[x];
    data[tot].to = y;
    data[tot].va = va;
    head[x] = tot;
}

bool bfs()
{
    memset(deep,0,sizeof(deep)); 
    deep[str] = 1;
    queue<int> q;
    q.push(str);
    while(!q.empty())
    {
        int from = q.front();q.pop();
        for(int i=head[from];i!=-1;i=data[i].net)
        {
            int to = data[i].to ;
            int va = data[i].va ;
            if(va&&(!deep[to]))
            {
                deep[to] = deep[from]+1;
                q.push(to);
                if(to==end)
                    return true;
            }
        }
    }
    return false;
}

int dinic(int from,int flow)
{
    if(from==end)
        return flow; 
    int rest = flow; 
    for(int i=head[from];i!=-1;i=data[i].net)
    {
        int to = data[i].to ;
        int va = data[i].va ;
        if(!rest)
            return flow;
        if(va&&deep[to]==deep[from]+1) 
        {
            int k = dinic(to,min(rest,va));
            if(k==0)
                deep[to] = 0;
            data[i].va -= k;
            if(data[i].va==0&&(n<to&&to<=2*n))
            {
                pre[to] = from;
                net[from] = to-n;
                pre[to-n] = from;
                net[from+n] = to-n;
            }
            data[i^1].va += k;
            rest -= k;
        }
    }
    return flow - rest;
}

int main()
{
    memset(head,-1,sizeof(head));
    memset(pre,-1,sizeof(pre));
    memset(net,-1,sizeof(net));
    scanf("%d%d",&n,&m);
    end = 2*n + 1;
    str = end + 1;
    for(int i=1;i<=n;i++)
    {
        add(str,i,1);
        add(i,str,0);
        add(i+n,end,1);
        add(end,i+n,0);
    }
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y+n,1);
        add(y+n,x,0);
    }
    while(bfs())
        ans += dinic(str,2e9);
    for(int i=1;i<=n;i++)
    {
        if(pre[i]==-1)
        {
            for(int j=i;j!=-1;j=net[j])
                printf("%d ",j);
            puts("");
        }
    }
    printf("%d\n",n-ans);
    return 0;
}