題意
Sol
看完題不難想到最小路徑覆蓋,但是帶權的咋做啊?qwqqq
首先冷靜思考一下:最小路徑覆蓋 = (n – ext{二分圖最大匹配數})
為什麼呢?首先最壞情況下是用(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
", anscost);
return 0;
}