Luogu P2050 [NOI2012]美食节 网络流
第一次写网络流的题解...
传送~
Description
题意:有
Solution
这题数据范围不大, 应该还是可以想到网络流(费用流)的. 把每道菜与源点连起来, 容量为
这样正确性应该是可以理解的, 根据费用不同进行分层建图.
然而这样貌似只能拿60pts, 点数和边数都太多了.
我们发现每个厨师一开始建的
于是我们可以先只建出第一层的图, 在用EK跑费用流时, 假如我们增广了一条经过了第
这样就可以使点数和边数都大大减少.
Code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3;
const int maxp = 1e4;
const int inf = 0x3f3f3f3f;
int n, m, cnt, flow, cost, S, T, tot, head[maxp+10], p[maxn+10], t[maxn+10][maxn+10], org[maxp+10], tmp[maxp+10], pre[maxp+10];
int inq[maxp+10], dis[maxp+10], a[maxp+10];
struct edge {
int from, to, nex, flow, cap, cost;
} edges[maxp*20+10];
void addedge(int from, int to, int cap, int cost) {
edges[tot] = (edge){from, to, head[from], 0, cap, cost}; head[from] = tot++;
edges[tot] = (edge){to, from, head[to], 0, 0, -cost}; head[to] = tot++;
}
int spfa() {
memset(inq, 0, sizeof(inq));
memset(dis, 0x3f, sizeof(dis));
queue<int> q; q.push(S); dis[S] = 0; a[S] = inf;
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = 0;
for (int i = head[u]; ~i; i = edges[i].nex) {
edge& e = edges[i];
if (dis[e.to] > dis[u]+e.cost && e.cap > e.flow) {
dis[e.to] = dis[u]+e.cost;
a[e.to] = min(a[u], e.cap-e.flow);
pre[e.to] = i;
if (!inq[e.to]) {
inq[e.to] = 1; q.push(e.to);
}
}
}
}
if (dis[T] >= inf) return 0;
cost += dis[T]*a[T];
flow += a[T];
for (int i = T; i != S; i = edges[pre[i]].from) {
edges[pre[i]^1].flow -= a[T];
edges[pre[i]].flow += a[T];
}
return 1;
}
void dinic() {
while (spfa()) {
int u = edges[pre[T]].from, i = org[u];
addedge(++cnt, T, 1, 0);
org[cnt] = i; ++tmp[i];
for (int j = 1; j <= n; ++j)
addedge(j, cnt, 1, tmp[i]*t[j][i]);
}
}
int main() {
memset(head, -1, sizeof(head));
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i)
scanf("%d", &p[i]);
cnt = n; S = ++cnt; T = ++cnt;
for (int i = 1; i <= n; ++i)
addedge(S, i, p[i], 0);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
scanf("%d", &t[i][j]);
for (int i = 1; i <= m; ++i) {
addedge(++cnt, T, 1, 0);
org[cnt] = i; ++tmp[i];
for (int j = 1; j <= n; ++j)
addedge(j, cnt, 1, tmp[i]*t[j][i]);
}
dinic();
printf("%d\n", cost);
return 0;
}