[NOI2012]美食节
嘟嘟嘟
这题思路和[SCOI2007]修车以及POJ3686 The Windy's都一样,只不过数据是加强版。
从\(n\)盘菜变成了\(p\)盘菜,暴力拆点建图就不好用了,所以得优化。
这个优化我觉得比较难想,因为网络流一般都是考建图,对算法本身并没有什么考察。但这个优化却得用到费用流的性质。
费用流的原理就是每一次用spfa找出一条增广路进行增广。所以我们一开始不用把所有边都建出来。在这道题中,一开始找到的增广路一定经过某一个厨师倒数第一个完成的某一盘菜的那个点,因此我们找到这个厨师后,把他倒数第二个完成的菜的点以及和他相邻的边加上。
这样我们跑了\(p\)次spfa,每一次只多加了\(n\)条边,所以总共这就加了\(n * p + n * 2 + m\)条边,复杂度就有了保证。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 105;
const int maxN = 1e5 + 5;
const int maxe = 5e6 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, t, tot;
int p[maxn], a[maxn][maxn];
struct Edge
{
int nxt, from, to, cap, cos;
}e[maxe];
int head[maxN], ecnt = -1;
In void addEdge(int x, int y, int w, int c)
{
e[++ecnt] = (Edge){head[x], x, y, w, c};
head[x] = ecnt;
e[++ecnt] = (Edge){head[y], y, x, 0, -c};
head[y] = ecnt;
}
bool in[maxN];
int dis[maxN], pre[maxN], flow[maxN];
In bool spfa()
{
Mem(dis, 0x3f), Mem(in, 0);
dis[0] = 0; flow[0] = INF;
queue<int> q; q.push(0); in[0] = 1;
while(!q.empty())
{
int now = q.front(); q.pop(); in[now] = 0;
for(int i = head[now], v; ~i; i = e[i].nxt)
{
if(dis[v = e[i].to] > dis[now] + e[i].cos && e[i].cap > 0)
{
dis[v] = dis[now] + e[i].cos;
flow[v] = min(flow[now], e[i].cap);
pre[v] = i;
if(!in[v]) q.push(v), in[v] = 1;
}
}
}
return dis[t] ^ INF;
}
int minCost = 0;
In void update()
{
int x = t;
while(x)
{
int i = pre[x];
e[i].cap -= flow[t];
e[i ^ 1].cap += flow[t];
x = e[i].from;
}
minCost += dis[t] * flow[t];
}
In int MCMF()
{
while(spfa())
{
update();
int x = e[pre[t]].from, y = (x - n) / tot + 1, z = (x - n) % tot;
addEdge(n + (y - 1) * tot + z + 1, t, 1, 0);
for(int i = 1; i <= n; ++i) addEdge(i, n + (y - 1) * tot + z + 1, 1, (z + 1) * a[i][y]);
}
return minCost;
}
int main()
{
Mem(head, -1);
n = read(), m = read();
for(int i = 1; i <= n; ++i)
{
p[i] = read(); tot += p[i];
addEdge(0, i, p[i], 0);
}
t = n + m * tot + 1;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j)
a[i][j] = read(), addEdge(i, n + (j - 1) * tot + 1, 1, a[i][j]);
for(int i = 1; i <= m; ++i) addEdge(n + (i - 1) * tot + 1, t, 1, 0);
write(MCMF()), enter;
return 0;
}