POJ 1201 Intervals(差分约束系统)

我们让xi表示[0,1,...,i-1]中选出数的个数,那么对于一行输入a,b,c,我们有x(b+1)-xa>=c。

特别注意一下隐含条件:0<=x(i+1)-xi<=1,然后建立约束图,spfa求一下最长路就成了。

(stl太慢了。。。慢的我都T了一次)

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 50005;

int fst[N], nxt[4 * N], to[N * 4], cost[N * 4], e;
int dis[N], n, q[N];
bool in[N];

void add(int u, int v, int c) {
	to[e] = v;
	cost[e] = c;
	nxt[e] = fst[u];
	fst[u] = e++;
}

void spfa() {
	memset(dis, -1, sizeof dis);
	memset(in, false, sizeof in);
	int head = 0, tail = 0;
	q[tail++] = n + 2;//super source
	in[n + 2] = true;
	dis[n + 2] = 0;
	while (head != tail) {
		int u = q[head++];
		if (head == N)head = 0;
		in[u] = false;
		for (int i = fst[u]; i != -1; i = nxt[i]) {
			int v = to[i], c = cost[i];
			if (dis[v] < dis[u] + c) {
				dis[v] = dis[u] + c;
				if (!in[v]) {
					q[tail++] = v;
					in[v] = true;
					if (tail == N)tail = 0;
				}
			}
		}
	}
}

int main() {
	int num; scanf("%d", &num);
	n = 0;
	e = 0;
	memset(fst, -1, sizeof fst);
	while (num--) {
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		add(a, b + 1, c);
		n = max(n, b + 1);
	}
	for (int i = 0; i <= n; i++) {
		add(n + 2, i, 0);
		add(i, i + 1, 0);
		add(i + 1, i, -1);
	}
	spfa();
	printf("%d\n", dis[n]);
	return 0;
}


你可能感兴趣的:(POJ 1201 Intervals(差分约束系统))