欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

BZOJ1927: [Sdoi2010]星际竞速(最小费用最大流 最小路径覆盖)

程序员文章站 2023-11-17 22:47:04
题意 "题目链接" Sol 看完题不难想到最小路径覆盖,但是带权的咋做啊?qwqqq 首先冷静思考一下:最小路径覆盖 = $n \text{二分图最大匹配数}$ 为什么呢?首先最坏情况下是用$n$条路径去覆盖(就是$n$个点),根据二分图的性质,每个点只能有一个和他配对,这样就保证了,每多出一个匹配 ......

题意

题目链接

sol

看完题不难想到最小路径覆盖,但是带权的咋做啊?qwqqq

首先冷静思考一下:最小路径覆盖 = \(n - \text{二分图最大匹配数}\)

为什么呢?首先最坏情况下是用\(n\)条路径去覆盖(就是\(n\)个点),根据二分图的性质,每个点只能有一个和他配对,这样就保证了,每多出一个匹配,路径数就会\(-1\)

扩展到有边权的图也是同理的,\(i\)表示二分图左侧的点,\(i'\)表示二分图右侧的点,对于两点\(u, v\),从\(u\)\(v'\)\((1, w_i)\)的边(前面是流量,后面是费用)

接下来从\(s\)\(i\)\((1, 0)\)的边,从\(i'\)\(t\)\((1, 0)\)的边,从\(s\)\(i'\)\((1, a_i)\)的边

跑最小费用最大流即可

#include<bits/stdc++.h>
#define chmin(x, y) (x = x < y ? x : y)
#define chmax(x, y) (x = x > y ? x : y)
using namespace std;
const int maxn = 1e6 + 10, inf = 1e9 + 10;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int n, m, s, t, dis[maxn], vis[maxn], pre[maxn], ansflow, anscost, a[maxn];
struct edge {
    int u, v, f, w, nxt;
}e[maxn];
int head[maxn], num = 0;
inline void add_edge(int x, int y, int f, int w) {
    e[num] = (edge) {x, y, f, w, head[x]}; head[x] = num++;    
}
inline void addedge(int x, int y, int f, int w) {
    add_edge(x, y, f, w); add_edge(y, x, 0, -w);
}
bool spfa() {
    queue<int> q; q.push(s);
    memset(dis, 0x3f, sizeof(dis));
    memset(vis, 0, sizeof(vis));
    dis[s] = 0;
    while(!q.empty()) {
        int p = q.front(); q.pop(); vis[p] = 0;
        for(int i = head[p]; ~i; i = e[i].nxt) {
            int to = e[i].v;
            if(e[i].f && dis[to] > dis[p] + e[i].w) {
                dis[to] = dis[p] + e[i].w; pre[to] = i;
                if(!vis[to]) vis[to] = 1, q.push(to);
            }
        }
    }
    return dis[t] <= inf;
}
void f() {
    int canflow = inf;
    for(int i = t; i != s; i = e[pre[i]].u) chmin(canflow, e[pre[i]].f);
    for(int i = t; i != s; i = e[pre[i]].u) e[pre[i]].f -= canflow, e[pre[i] ^ 1].f += canflow;
    anscost += canflow * dis[t];
}
void mcmf() {
    while(spfa()) f();
}
int main() {   
    memset(head, -1, sizeof(head));
    n = read(); m = read(); s = n * 2 + 2, t = n * 2 + 3;
    for(int i = 1; i <= n; i++) a[i] =read(), addedge(s, i, 1, 0), addedge(i + n, t, 1, 0), addedge(s, i + n, 1, a[i]);
    for(int i = 1; i <= m; i++) {
        int x = read(), y = read(), v = read();
        if(x > y) swap(x, y);
        addedge(x, y + n, 1, v);
    }
    mcmf();
    printf("%d\n", anscost);
    return 0;
}