其他分享
首页 > 其他分享> > BZOJ1927: [Sdoi2010]星际竞速(最小费用最大流 最小路径覆盖)

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

作者:互联网

题意

题目链接

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;
}

标签:二分,竞速,int,路径,最小,Sdoi2010,vis,while,dis
来源: https://blog.51cto.com/u_15239936/2868685