[ZPG TEST 115] 种树【差分约束】

4. 种树

trees.pas/c/cpp

【问题描述】

一条街的一边有几座房子。因为环保原因居民想要在路边种些树。路边的地区被分割成块,并被编号为1..n。每个块的大小为一个单位尺寸并最多可种一棵树。每个居民想在门前种些树并指定了三个号码b,e,t。这三个数表示该居民想在b和e之间最少种t棵树。当然,b<=e,居民必须保证在指定地区不能种多于地区被分割成块数的树,即要求t<=e-b+1。允许居民想种树的各自区域可以交叉。出于资金短缺的原因,环保部门请你求出能够满足所有居民的要求,需要种树的最少数量。

 

【文件输入】

第一行为n,表示区域的个数;

第二行为h,表示房子的数目;

下面h行描述居民的需要:b e t (0<b<=e<=30000,r<=e-b+1) 分别用一个空格分开。

 

【文件输出】

输出为满足所有要求的最少树的数量。

 

【样例输入】

9

4

1 4 2

4 6 2

8 9 2

3 5 2

 

【样例输出】

5

 

【数据规模】

30%的数据满足0<n<=1000;0<h<=500

100%的数据满足n<=30000;h<=5000

 

 

 

此题乃差分约束裸题,只恨当时不会啊。

令a[i]表示i位置有没有种树,令s[i]表示a数列的前缀和,则对于题目输入的一系列b,e,t转化为一系列不等式s[e] - s[b - 1] >= t,很显然这就是一个差分约束系统。把不等式写成大于等于的形式,是因为这样子就是求最长路,求最长路得出的结果就是最小的一组解集,求最短路得出的结果就是最大的一组解集,不予证明。注意还有两个条件,对于任意的i,s[i] - s[i - 1] >= 0,s[i - 1] - s[i] >= -1.

#include <cstdio>
#include <cstring>

const int maxn = 30005, maxe = 80005;

int n, h, t1, t2, t3;
int head[maxn], to[maxe], next[maxe], w[maxe], lb;
int que[maxn], head_, tail, d[maxn];
bool inq[maxn];

inline void ist(int aa, int ss, int ww) {
	to[lb] = ss;
	next[lb] = head[aa];
	head[aa] = lb;
	w[lb] = ww;
	++lb;
}

int main(void) {
	freopen("trees.in", "r", stdin);
	freopen("trees.out", "w", stdout);
	memset(head, -1, sizeof head);
	memset(next, -1, sizeof next);
	scanf("%d", &n);
	scanf("%d", &h);
	while (h--) {
		scanf("%d%d%d", &t1, &t2, &t3);
		ist(t1 - 1, t2, t3);
	}
	for (int i = 0; i < n; ++i) {
		ist(i, i + 1, 0);
		ist(i + 1, i, -1);
	}
	
	memset(d, -0x3c, sizeof d);
	que[tail++] = 0;
	inq[0] = true;
	d[0] = 0;
	while (head_ != tail) {
		h = que[head_++];
		inq[h] = false;
		if (head_ == n + 1) {
			head_ = 0;
		}
		for (int j = head[h]; j != -1; j = next[j]) {
			if (d[to[j]] < d[h] + w[j]) {
				d[to[j]] = d[h] + w[j];
				if (!inq[to[j]]) {
					inq[to[j]] = true;
					que[tail++] = to[j];
					if (tail == n + 1) {
						tail = 0;
					}
				}
			}
		}
	}
	printf("%d\n", d[n]);
	return 0;
}

  

posted @ 2016-11-15 20:01  ciao_sora  阅读(304)  评论(0编辑  收藏  举报