luogu P2764 最小路径覆盖问题

Posted gredcomet

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了luogu P2764 最小路径覆盖问题相关的知识,希望对你有一定的参考价值。

最小路径覆盖=节点数-最大匹配数,拆成二分图跑dinic/匈牙利即可,注意输出路径的时候判断拆成的入点和出点和另加的反向边

技术图片
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;

const int maxm = 2e4+5;
const int INF = 0x3f3f3f3f;

struct edge{
    int u, v, cap, flow, nex;
} edges[maxm];

int head[maxm], cur[maxm], cnt, n, level[333];
bool vis[333];

void init() {
    memset(head, -1, sizeof(head));
}

void add(int u, int v, int cap) {
    edges[cnt] = edge{u, v, cap, 0, head[u]};
    head[u] = cnt++;
}

void addedge(int u, int v, int cap) {
    add(u, v, cap), add(v, u, 0);
}

void bfs(int s) {
    memset(level, -1, sizeof(level));
    queue<int> q;
    level[s] = 0;
    q.push(s);
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        for(int i = head[u]; i != -1; i = edges[i].nex) {
            edge& now = edges[i];
            if(now.cap > now.flow && level[now.v] < 0) {
                level[now.v] = level[u] + 1;
                q.push(now.v);
            }
        }
    }
}

int dfs(int u, int t, int f) {
    if(u == t) return f;
    for(int& i = cur[u]; i != -1; i = edges[i].nex) {
        edge& now = edges[i];
        if(now.cap > now.flow && level[u] < level[now.v]) {
            int d = dfs(now.v, t, min(f, now.cap - now.flow));
            if(d > 0) {
                now.flow += d;
                edges[i^1].flow -= d;
                return d;
            }

        }
    }
    return 0;
}

int dinic(int s, int t) {
    int maxflow = 0;
    for(;;) {
        bfs(s);
        if(level[t] < 0) break;
        memcpy(cur, head, sizeof(head));
        int f;
        while((f = dfs(s, t, INF)) > 0)
            maxflow += f;
    }
    return maxflow;
}

void print(int u, int s, int t) {
    if(vis[u]) return;
    vis[u] = true;
    cout << u << " ";
    for(int i = head[u]; i != -1; i = edges[i].nex) {
        auto now = edges[i];
        if(now.flow && now.v != s)
            if(!vis[now.v-n])
                print(now.v-n,s,t);
    }
}

void run_case() {
    init();
    int m, u, v; 
    cin >> n >> m;
    int s = 0, t = (n<<1)+2;
    for(int i = 0; i < m; ++i) {
        cin >> u >> v;
        addedge(u, v+n, 1);
    }
    for(int i = 1; i <= n; ++i) {
        addedge(s, i, 1);
        addedge(i+n, t, 1);
    }
    int ans = n - dinic(s, t);
    
    for(int i = 1; i <= n; ++i) {
        if(!vis[i]) {
            print(i,s,t);
            cout << "
";
        }
    }
    cout << ans;
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    run_case();
    cout.flush();
    return 0;
}
View Code

 

以上是关于luogu P2764 最小路径覆盖问题的主要内容,如果未能解决你的问题,请参考以下文章

luogu P2764 最小路径覆盖问题

luogu P2764 最小路径覆盖问题

P2764 最小路径覆盖问题

P2764 最小路径覆盖问题 网络流输出方案

P2764 最小路径覆盖问题

P2764 最小路径覆盖问题