【BZOJ1930】[Shoi2003]pacman 吃豆豆【最大费用最大流】

【题目链接】

被卡的不要不要的= =

hzwer的建图似乎是错的,按照这个过了

【jiangyuze831的题解】

/* Think Thank Thunk */
#include 
#include 
#include 

using namespace std;

const int maxn = 4005, maxm = 4100005, maxq = 100000, inf = 0x3f3f3f3f;

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

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

struct data {
	int x, y;

	bool operator < (const data &a) const {
		return x != a.x ? x < a.x : y < a.y;
	}
} po[2005];

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;
	int h = 0, t = 0, u, i; depth[q[t++] = bg] = 0;
	while(h != t) for(i = head[u = q[h]], h == maxq - 1 ? h = 0 : h++, vis[u] = 0; ~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, t == maxq - 1 ? t = 0 : t++;
	}
	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 += flow * g[way[u]].c;
	return res;
}

int main() {
	n = iread(); bg = 0; ed = (n << 1) + 2;
	for(int i = 0; i <= ed; i++) head[i] = -1; cnt = 0;
	for(int i = 1; i <= n; i++) po[i].x = iread(), po[i].y = iread();
	sort(po + 1, po + 1 + n);

	for(int i = 1; i <= n; i++) {
		int upb = inf;
		for(int j = i + 1; j <= n; j++) {
			if(po[i].y <= po[j].y && po[j].y < upb)
				insert(i + n, j, 2, 0);
			if(po[i].y <= po[j].y)
				upb = min(upb, po[j].y);
		}
	}

	int s = ed - 1;
	insert(bg, s, 2, 0);
	for(int i = 1; i <= n; i++) {
		insert(s, i, 1, 0);
		insert(i, i + n, 1, 1);
		insert(i, i + n, 1, 0);
		insert(i + n, ed, 1, 0);
	}

	int ans = 0;
	while(spfa()) ans += back();
	printf("%d\n", ans);

	return 0;
}


你可能感兴趣的:(网络流)