描述
Farmer John's cows have discovered that the clover growing along the ridge of the hill in his field is particularly good. To keep the clover watered, Farmer John is installing water sprinklers along the ridge of the hill.
To make installation easier, each sprinkler head must be installed along the ridge of the hill (which we can think of as a one-dimensional number line of length L (1 <= L <= 1,000,000); L is even).
Each sprinkler waters the ground along the ridge for some distance in both directions. Each spray radius is an integer in the range A..B (1 <= A <= B <= 1000). Farmer John needs to water the entire ridge in a manner that covers each location on the ridge by exactly one sprinkler head. Furthermore, FJ will not water past the end of the ridge in either direction.
Each of Farmer John's N (1 <= N <= 1000) cows has a range of clover that she particularly likes (these ranges might overlap). The ranges are defined by a closed interval (S,E). Each of the cow's preferred ranges must be watered by a single sprinkler, which might or might not spray beyond the given range.
Find the minimum number of sprinklers required to water the entire ridge without overlap.
输入
* Line 1: Two space-separated integers: N and L
* Line 2: Two space-separated integers: A and B
* Lines 3..N+2: Each line contains two integers, S and E (0 <= S < E <= L) specifying the start end location respectively of a range preferred by some cow. Locations are given as distance from the start of the ridge and so are in the range 0..L.
输出
* Line 1: The minimum number of sprinklers required. If it is not possible to design a sprinkler head configuration for Farmer John, output -1.
样例输入
2 8
1 2
6 7
3 6
样例输出
3
这个题目程设课上田永鸿老师讲了单调队列的做法,虽然以前自己也一直都是用单调队列优化动态规划的,而且用的非常之多,但是今天突然奇想
觉得用单调队列优化其实用普通的优先队列也可以优化(当然了 普通的优先队列优化 我写出来复杂度要比单调队列的复杂度多一个logN)
因为每个对于进队列一次出队列一次,我们只要维护一段区间内的最优值即可,当然随着i往后移动,可以转移的区间也往后移动,我们不马上
删除不在区间内的值,而是等取出来时发现不符合区间的要求再将它删除即可,直到出现的最小值是在这个区间内。
这样的复杂度就是NlogN。这样做看似和线段树差不多。 但是这题的想法和之前做的STL专项练习中的题目G是一样的。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 1000000+10;
int n,l,A,B,s,e;
struct Node
{
int Pos, Cnt;
bool operator<(const Node & a)const{
return Cnt>a.Cnt;
}
}F[MAXN];
int cow[MAXN];
priority_queue<Node> q;
int main()
{
cin>>n>>l>>A>>B;A*=2;B*=2;
for (int i = 1; i <= n; ++i){
scanf("%d%d",&s,&e);
cow[s+1]++; cow[e]--;
}
int cowCnt = 0; q.push(F[0]);
for (int i = 2; i <= l;i+=2)
{
cowCnt +=cow[i]+cow[i-1];
if (cowCnt==0 && i>=A){
while (!q.empty()){
if (i-q.top().Pos>B) { q.pop(); continue;}
F[i].Pos = i; F[i].Cnt = q.top().Cnt+1;
break;
}
}
if (i>=A && F[i-A+1].Cnt != 0) q.push(F[i-A+1]);
if (i+1>=A && F[i-A+2].Cnt != 0) q.push(F[i-A+2]);
}
if (F[l].Cnt ==0) cout<<-1<<endl;else
cout<< F[l].Cnt << endl;
return 0;
}