POJ1201 Intervals

一道差分约束

原题链接

定义(f[x])表示(0sim x)间最少选择几个数,则(f[b_i]-f[a_i-1]geqslant c_i)
显然的差分约束。
另有条件(f[x]-f[x-1]geqslant 0,f[x]-f[x-1]leqslant 1)
按上述条件建图跑最长路即可,注意题目保证(c_ileqslant b_i-a_i+1),所以不存在正环,即无解的情况。

#include<cstdio>
#include<cstring>
using namespace std;
const int N = 5e4 + 10;
const int M = 1e5 + 5e4 + 10;
const int K = 5e4 + 2;
int fi[N], di[M], da[M], ne[M], dis[N], q[N << 4], l;
bool v[N];
inline int re()
{
	int x = 0;
	char c = getchar();
	bool p = 0;
	for (; c<'0' || c>'9'; c = getchar())
		p |= c == '-';
	for (; c >= '0'&&c <= '9'; c = getchar())
		x = x * 10 + (c - '0');
	return p ? -x : x;
}
inline void add(int x, int y, int z)
{
	di[++l] = y;
	da[l] = z;
	ne[l] = fi[x];
	fi[x] = l;
}
int main()
{
	int i, n, x, y, z, head = 0, tail = 1;
	n = re();
	memset(dis, 250, sizeof(dis));
	for (i = 1; i <= n; i++)
	{
		x = re() + 2;
		y = re() + 2;
		z = re();
		add(x - 1, y, z);
	}
	for (i = 1; i <= K; i++)
	{
		add(i, i + 1, 0);
		if (i ^ 1)
			add(i, i - 1, -1);
	}
	dis[1] = 0;
	q[1] = 1;
	while (head != tail)
	{
		x = q[++head];
		v[x] = 0;
		for (i = fi[x]; i; i = ne[i])
		{
			y = di[i];
			if (dis[y] < dis[x] + da[i])
			{
				dis[y] = dis[x] + da[i];
				if (!v[y])
				{
					q[++tail] = y;
					v[y] = x;
				}
			}
		}
	}
	printf("%d", dis[K]);
	return 0;
}
原文地址:https://www.cnblogs.com/Iowa-Battleship/p/9618603.html