【BZOJ1283】序列【最大费用最大流】

【题目链接】

做了才发现是论文题,但是和论文上建图不一样。。杨沐《浅析信息学中的“分”与“合”》

看的【POPOQQQ的题解】大爷的题解orz。


队列似乎开小了,TLE了一次。

/* Pigonometry */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 1005, maxm = 5005, maxq = 50000, inf = 0x3f3f3f3f;

int n, m, k, head[maxn], cnt, num[maxn], bg, ed, depth[maxn], vis[maxn], way[maxn], q[maxq];

struct _edge {
	int v, w, c, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v, int w, int c) {
	g[cnt] = (_edge){v, w, c, head[u]};
	head[u] = cnt++;
}

inline void insert(int u, int v, int w, int c) {
	add(u, v, w, c); add(v, u, 0, -c);
}

inline bool spfa() {
	for(int i = 0; i <= ed; i++) depth[i] = -inf, vis[i] = 0;
	int h = 0, t = 0, u, i; depth[q[t++] = bg] = 0; vis[bg] = 1;
	while(h != t) {
		for(i = head[u = q[h++]]; ~i; i = g[i].next) if(g[i].w && depth[g[i].v] < depth[u] + g[i].c) {
			depth[g[i].v] = depth[u] + g[i].c;
			way[g[i].v] = i;
			if(!vis[g[i].v]) vis[q[t++] = g[i].v] = 1;
		}
		vis[u] = 0;
	}
	return depth[ed] != -inf;
}

inline int back() {
	int flow = inf, res = 0;
	for(int u = ed; u != bg; u = g[way[u] ^ 1].v) flow = min(flow, g[way[u]].w);
	for(int u = ed; u != bg; u = g[way[u] ^ 1].v) g[way[u]].w -= flow, g[way[u] ^ 1].w += flow, res += g[way[u]].c * flow;
	return res;
}

int main() {
	n = iread(); m = iread(); k = iread();
	bg = 0; ed = n + 1;
	for(int i = 0; i <= ed; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i <= n; i++) num[i] = iread();

	insert(bg, 1, k, 0);
	for(int i = 1; i <= n; i++) {
		insert(i, min(i + m, ed), 1, num[i]);
		insert(i, i + 1, k, 0);
	}

	int ans = 0;
	while(spfa()) ans += back();

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ1283】序列【最大费用最大流】)