洛谷 P3980 [NOI2008]志愿者招募（网络流-费用流）

题目链接

#pragma comment(linker, "/STACK:102400000,102400000")

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>

const int mod = 998244353;
const int maxn = 1e5 + 5;
const int inf = 1e9;
const long long onf = 1e18;
#define me(a, b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI 3.14159265358979323846
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int minflow[maxn], pre[maxn];
int dis[maxn];
bool vis[maxn];
int n, m, st, ed;
int mincost;
int Max = 0, a[maxn];
struct node {
int v, next, flow, val;
} maps[maxn << 2];

inline void add_edge(int u, int v, int flow, int val) {
maps[tot].v = v;
maps[tot].flow = flow;
maps[tot].val = val;
}

inline void ins(int u, int v, int flow, int val) {
}

inline bool bfs() {
fill(dis, dis + maxn, inf);
dis[st] = 0, pre[st] = -1, minflow[st] = inf;
queue<int> q;
q.push(st);
while (!q.empty()) {
int u = q.front();
q.pop(), vis[u] = 0;
for (int i = head[u]; i != -1; i = maps[i].next) {
int v = maps[i].v, flow = maps[i].flow, val = maps[i].val;
if (flow && dis[v] > dis[u] + val) {
dis[v] = dis[u] + val;
pre[v] = i;
minflow[v] = min(minflow[u], flow);
if (!vis[v])
q.push(v), vis[v] = 1;
}
}
}
return dis[ed] < inf;
}

inline void MCMF() {
while (bfs()) {
for (int i = pre[ed]; i != -1; i = pre[maps[i ^ 1].v]) {
maps[i].flow -= minflow[ed];
maps[i ^ 1].flow += minflow[ed];
}
//     cout << minflow[ed] << " " << dis[ed] << endl;
mincost += minflow[ed] * dis[ed];
}
}

inline void init() {
tot = mincost = 0;
}

void build_inf() {///建inf-a[i]的免费边
for (int i = 1; i <= n; i++) {
ins(i, i + 1, inf - a[i], 0);
}
for (int i = 1; i <= m; i++) {
int u, v, val;
scanf("%d%d%d", &u, &v, &val);
ins(u, v + 1, inf, val);
}
ins(st, 1, inf, 0), ins(n + 1, ed, inf, 0);
}

void build_max() {///建max-a[i]的免费边
for (int i = 1; i <= n; i++) {
add_edge(i, i + 1, Max - a[i], 0);
add_edge(i + 1, i, inf - a[i], 0);///因为可能出现不跑这条免费边情况更优的情况，所以要给足反悔的余地
}
for (int i = 1; i <= m; i++) {
int u, v, val;
scanf("%d%d%d", &u, &v, &val);
ins(u, v + 1, inf, val);
}
ins(st, 1, Max, 0), ins(n + 1, ed, Max, 0);
}

int main() {
init();
scanf("%d%d", &n, &m);
st = 0, ed = n + 2;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
Max = max(Max, a[i]);
}
build_inf();
///build_max();
MCMF();
printf("%d\n", mincost);
return 0;
}

11-29 466

09-22 113

08-11 449

02-10 649

09-19 226

12-02 129

07-18 180

02-15 46

03-05 28

02-11 66

网络流/费用流(洛谷 P3980 [NOI2008]志愿者招募)

©️2020 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。