bzoj-1834 network 网络扩容 【网络流】

时间:2024-04-06 17:04:23

  这题就是复习下网络流。

 #include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define drep(i, a, b) for (int i = a; i >= b; i--)
#define REP(i, a, b) for (int i = a; i < b; i++)
#define mp make_pair
#define pb push_back
#define clr(x) memset(x, 0, sizeof(x))
#define xx first
#define yy second
using namespace std;
typedef long long i64;
typedef pair<int, int> pii;
const int inf = ~0U >> ;
const i64 INF = ~0ULL >> ;
//******************************** const int maxn = , maxm = ; struct Ed {
int u, v, nx, c, w; Ed() {}
Ed(int _u, int _v, int _nx, int _c, int _w) :
u(_u), v(_v), nx(_nx), c(_c), w(_w) {}
} E[maxm << ];
int G[maxn], edtot, cur[maxn];
void addedge(int u, int v, int c, int w) {
E[edtot] = Ed(u, v, G[u], c, w);
G[u] = edtot++;
E[edtot] = Ed(v, u, G[v], , -w);
G[v] = edtot++;
} int level[maxn], s , t;
bool bfs() {
static int que[maxn]; int qh(), qt();
clr(level);
level[que[++qt] = s] = ;
while (qh != qt) {
int x = que[++qh];
for (int i = G[x]; i != -; i = E[i].nx) if (!level[E[i].v] && E[i].c) {
level[que[++qt] = E[i].v] = level[x] + ;
}
}
return !!level[t];
}
int dfs(int u, int rm) {
if (u == t) return rm;
int rm1 = rm;
for (int &i = cur[u]; i != -; i = E[i].nx) {
if (level[E[i].v] == level[u] + && E[i].c) {
int flow = dfs(E[i].v, min(rm, E[i].c));
E[i].c -= flow, E[i ^ ].c += flow;
if ((rm -= flow) == ) break;
}
}
if (rm1 == rm) level[u] = ;
return rm1 - rm;
} int dis[maxn], vis[maxn];
bool spfa() {
static int que[maxn]; int qh(), qt();
memset(dis, 0x3f, sizeof(dis));
clr(vis);
dis[que[++qt] = s] = , vis[s] = ;
while (qh != qt) {
int x = que[++qh]; vis[x] = ;
for (int i = G[x]; i != -; i = E[i].nx) {
if (E[i].c && dis[E[i].v] > dis[x] + E[i].w) {
dis[E[i].v] = dis[x] + E[i].w;
if (!vis[E[i].v]) que[++qt] = E[i].v, vis[E[i].v] = ;
}
}
}
return dis[t] != 0x3f3f3f3f;
}
int ret;
int dinic(int u, int rm) {
vis[u] = ;
if (u == t) return rm;
int rm1 = rm;
for (int i = G[u]; i != -; i = E[i].nx) {
if (dis[E[i].v] == dis[u] + E[i].w && E[i].c && !vis[E[i].v]) {
int flow = dinic(E[i].v, min(rm , E[i].c));
E[i].c -= flow, E[i ^ ].c += flow;
ret += flow * E[i].w;
if ((rm -= flow) == ) break;
}
}
if (rm1 == rm) dis[u] = ;
return rm1 - rm;
} int main() {
int n, m, K;
scanf("%d%d%d", &n, &m, &K);
memset(G, -, sizeof(G));
rep(i, , m) {
int x, y, c, w;
scanf("%d%d%d%d", &x, &y, &c, &w);
addedge(x, y, c, w);
addedge(x, y, c, );
}
s = , t = n + ; addedge(s, , 0x3f3f3f3f, ), addedge(n, t, 0x3f3f3f3f, );
int ans();
while (bfs()) memcpy(cur, G, sizeof(G)), ans += dfs(s, 0x3f3f3f3f);
printf("%d ", ans >> );
for (int i = ; i <= edtot; i += ) {
if (E[i].w == ) E[i].c += E[i ^ ].c, E[i ^ ].c = ;
else E[i].c = 0x3f3f3f3f, E[i ^ ].c = ;
if (E[i].u == s) E[i].c = (ans >> ) + K;
}
while (spfa()) clr(vis), dinic(s, 0x3f3f3f3f);
printf("%d\n", ret);
}