BZOJ 3314: [Usaco2013 Nov]Crowded Cows( 单调队列 )

从左到右扫一遍, 维护一个单调不递减队列. 然后再从右往左重复一遍然后就可以统计答案了。

----------------------------------------------------------------------------

#include<bits/stdc++.h>
 
#define rep(i, n) for(int i = 0; i < n; ++i)
#define clr(x, c) memset(x, c, sizeof(x))
#define foreach(i, x) for(__typeof(x.begin()) i = x.begin(); i != x.end(); i++)
 
using namespace std;
 
const int maxn = 50009;
 
struct R {
int p, h;
inline void Read() {
scanf("%d%d", &p, &h);
}
bool operator < (const R &t) const {
return p < t.p;
}
} A[maxn];
 
bool l[maxn], r[maxn];
int n, d;
deque<int> Q;
 
int main() {
freopen("test.in", "r", stdin);
cin >> n >> d;
rep(i, n) A[i].Read();
sort(A, A + n);
clr(l, 0), clr(r, 0);
while(!Q.empty()) Q.pop_back();
rep(i, n) {
R* h = A + i;
while(!Q.empty() && A[Q.front()].p + d < h->p) Q.pop_front();
if(!Q.empty() && A[Q.front()].h >= 2 * h->h) l[i] = true;
while(!Q.empty() && A[Q.back()].h < h->h) Q.pop_back();
Q.push_back(i);
}
while(!Q.empty()) Q.pop_back();
for(int i = n - 1; ~i; i--) {
R* h = A + i;
while(!Q.empty() && A[Q.front()].p - d > h->p) Q.pop_front();
if(!Q.empty() && A[Q.front()].h >= 2 * h->h) r[i] = true;
while(!Q.empty() && A[Q.back()].h < h->h) Q.pop_back();
Q.push_back(i);
}
int ans = 0;
rep(i, n) if(l[i] && r[i]) ans++;
cout << ans << "\n";
return 0;
}

----------------------------------------------------------------------------

3314: [Usaco2013 Nov]Crowded Cows

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 120  Solved: 85
[Submit][Status][Discuss]

Description

 Farmer John's N cows (1 <= N <= 50,000) are grazing along a one-dimensional fence. Cow i is standing at location x(i) and has height h(i) (1 <= x(i),h(i) <= 1,000,000,000). A cow feels "crowded" if there is another cow at least twice her height within distance D on her left, and also another cow at least twice her height within distance D on her right (1 <= D <= 1,000,000,000). Since crowded cows produce less milk, Farmer John would like to count the number of such cows. Please help him.

N头牛在一个坐标轴上,每头牛有个高度。现给出一个距离值D。

如果某头牛在它的左边,在距离D的范围内,如果找到某个牛的高度至少是它的两倍,且在右边也能找到这样的牛的话。则此牛会感觉到不舒服。

问有多少头会感到不舒服。

Input

* Line 1: Two integers, N and D.

* Lines 2..1+N: Line i+1 contains the integers x(i) and h(i). The locations of all N cows are distinct.

Output

* Line 1: The number of crowded cows.

Sample Input

6 4
10 3
6 2
5 3
9 7
3 6
11 2

INPUT DETAILS: There are 6 cows, with a distance threshold of 4 for feeling crowded. Cow #1 lives at position x=10 and has height h=3, and so on.

Sample Output

2
OUTPUT DETAILS: The cows at positions x=5 and x=6 are both crowded.

HINT

Source

 

posted @ 2015-07-26 19:51  JSZX11556  阅读(274)  评论(0编辑  收藏  举报