正题
luogu 3980
题目大意
有n个时刻,第i个时刻需要aia_iai个志愿者,有m类志愿者,第j类可以从ljl_jlj做到rjr_jrj,代价为wjw_jwj,数量无限,问你使所有时刻志愿者个数都足够的最小代价
解题思路
经典的线性规划
从i到i+1连一条流量inf−aiinf-a_iinf−ai费用0的边,然后每类志愿者从ljl_jlj向rjr_jrj连流量inf,费用wjw_jwj的边
然后s到1,n+1到t连流量inf费用0的边(n+1是因为n的需求要存到n→n+1n\to n+1n→n+1的边上)
跑费用流,这样使得总流量为inf,费用最小
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define N 1010
using namespace std;
int n, m, x, y, s, t, tot, p[N], h[N], fr[N];
ll z, ans, b[N], f[N];
queue<int>d;
struct rec
{int to, next;ll f, c;
}e[N<<5];
const ll inf = 1e15;
void add(int x, int y, ll z, ll k)
{e[++tot].to = y;e[tot].f = z;e[tot].c = k;e[tot].next = h[x];h[x] = tot;e[++tot].to = x;e[tot].f = 0;e[tot].c = -k;e[tot].next = h[y];h[y] = tot;return;
}
bool bfs()
{memset(b, 0x7f, sizeof(b));memset(f, 0, sizeof(f));d.push(s);p[s] = 1;b[s] = 0;f[s] = inf;while(!d.empty()){int u = d.front();d.pop();for (int i = h[u]; i; i = e[i].next){int v = e[i].to;if (e[i].f && b[u] + e[i].c < b[v]){b[v] = b[u] + e[i].c;f[v] = min(f[u], e[i].f);fr[v] = i;if (!p[v]){p[v] = 1;d.push(v);}}}p[u] = 0;}return f[t];
}
void dfs()
{int now = t;while(fr[now]){e[fr[now]].f -= f[t];e[fr[now]^1].f += f[t];now = e[fr[now]^1].to;}ans += f[t] * b[t];
}
int main()
{scanf("%d%d", &n, &m);s = n + 2;t = n + 3;tot = 1;for (int i = 1; i <= n; ++i){scanf("%lld", &z);add(i, i + 1, inf - z, 0);}add(s, 1, inf, 0);add(n + 1, t, inf, 0);for (int i = 1; i <= m; ++i){scanf("%d%d%lld", &x, &y, &z);add(x, y + 1, inf, z);}while(bfs())dfs();printf("%lld", ans);return 0;
}