洛谷P2469 星际竞速

时间:2022-05-03 06:01:10

上下界费用流比较无脑,提供一种更巧妙的费用流,无需上下界。

洛谷P2469 星际竞速

 #include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring> const int N = , M = , INF = 0x3f3f3f3f; struct Edge {
int nex, v, c, len;
}edge[M << ]; int top = ; int e[N], d[N], vis[N], pre[N], flow[N];
std::queue<int> Q; inline void add(int x, int y, int z, int w) {
top++;
edge[top].v = y;
edge[top].c = z;
edge[top].len = w;
edge[top].nex = e[x];
e[x] = top; top++;
edge[top].v = x;
edge[top].c = ;
edge[top].len = -w;
edge[top].nex = e[y];
e[y] = top;
return;
} inline bool SPFA(int s, int t) {
memset(d, 0x3f, sizeof(d));
d[s] = ;
flow[s] = INF;
vis[s] = ;
Q.push(s);
while(!Q.empty()) {
int x = Q.front();
Q.pop();
vis[x] = ;
for(int i = e[x]; i; i = edge[i].nex) {
int y = edge[i].v;
if(edge[i].c && d[y] > d[x] + edge[i].len) {
d[y] = d[x] + edge[i].len;
pre[y] = i;
flow[y] = std::min(flow[x], edge[i].c);
if(!vis[y]) {
vis[y] = ;
Q.push(y);
}
}
}
}
return d[t] < INF;
} inline void update(int s, int t) {
int temp = flow[t];
while(t != s) {
int i = pre[t];
edge[i].c -= temp;
edge[i ^ ].c += temp;
t = edge[i ^ ].v;
}
return;
} inline int solve(int s, int t, int &cost) {
int ans = ;
cost = ;
while(SPFA(s, t)) {
ans += flow[t];
cost += flow[t] * d[t];
update(s, t);
}
return ans;
} int main() {
int n, m;
scanf("%d%d", &n, &m);
int s = n * + ;
int t = s + , S = s + , T = s + , O = s + ;
for(int i = , x; i <= n; i++) {
scanf("%d", &x);
add(O, i, , x);
add(i + n, O, INF, );
// add(i, i + n, 1, 0);
add(S, i + n, , );
add(i, T, , );
add(i + n, t, , );
}
add(s, O, , );
for(int i = , x, y, z; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
if(x > y) {
std::swap(x, y);
}
add(x + n, y, INF, z);
}
add(t, s, INF, ); int ans;
solve(S, T, ans);
printf("%d", ans);
return ;
}

上下界费用流AC代码