洛谷 P1250 种树
Description
一条街的一边有几座房子。因为环保原因居民想要在路边种些树。路边的地区被分割成块,并被编号成1..N。每个部分为一个单位尺寸大小并最多可种一棵树。每个居民想在门前种些树并指定了三个号码B,E,T。这三个数表示该居民想在B和E之间最少种T棵树。当然,B≤E,居民必须记住在指定区不能种多于区域地块数的树,所以T≤E-B+l。居民们想种树的各自区域可以交叉。你的任务是求出能满足所有要求的最少的树的数量。
写一个程序完成以下工作:
Input
第一行包含数据N,区域的个数(0<N≤30000);
第二行包含H,房子的数目(0<H≤5000);
下面的H行描述居民们的需要:B E T,0<B≤E≤30000,T≤E-B+1。
Output
- 输出文件只有一行写有树的数目
Sample Input
9
4
1 4 2
4 6 2
8 9 2
3 5 2
Sample Output
5
题解:
- 差分约束。
- 这是一道变式题。妙题,妙不可言。
- 首先设dis(i)表示前i个位置的树木之和(本质就是前缀和)
- 则对于每组要求a、b、c。则有dis(b) - dis(a - 1) >= c。看看,这是什么!?
- 不等式!
- 那么m个要求就抽象出了一个不等式组。
- 差分约束走起!
- 但是,写完之后你会发现你WA了。观察这题到底跟以往的差分约束有何不同。注意题目中有这么一句话:“每个部分为一个单位尺寸大小并最多可种一棵树”。也就是说一个位置至多只能种1棵树。把它抽象成不等式:0 <= dis[x] - dis[x - 1] <= 1
- 差分约束走起!
- 这次就愉快的A了。
- 好吧再次总结差分约束的要点
- 先找出明显的不等式
- 根据题目的特点,找出隐藏的不等式
- 用不等式建图
- 得出结果
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define N 100005
using namespace std;
struct E {int next, to, dis;} e[N];
int n, m, num;
int h[N], dis[N];
bool vis[N];
int read()
{
int x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x;
}
void add(int u, int v, int w)
{
e[++num].next = h[u];
e[num].to = v;
e[num].dis = w;
h[u] = num;
}
void spfa()
{
queue<int> que;
memset(dis, -0x3f, sizeof(dis));
dis[n + 1] = 0, vis[n + 1] = 1, que.push(n + 1);
while(!que.empty())
{
int now = que.front();
que.pop(); vis[now] = 0;
for(int i = h[now]; i != 0; i = e[i].next)
if(dis[now] + e[i].dis > dis[e[i].to])
{
dis[e[i].to] = dis[now] + e[i].dis;
if(!vis[e[i].to])
vis[e[i].to] = 1, que.push(e[i].to);
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int a = read(), b = read(), c = read();
add(a - 1, b, c);
}
for(int i = 1; i <= n; i++)
add(i - 1, i, 0), add(i, i - 1, -1);
for(int i = 0; i <= n; i++) add(n + 1, i, 0);
spfa();
cout << dis[n];
return 0;
}