二分查找
upper_bound(front, rear, x) (front rear 都是迭代器 返回>x的第一个数的迭代器)
lower_bound(front, rear, x) 返回<=x 的第一个数的迭代器
思路: 对桥的高度进行排序,对于每次涨的最高水位水位与上一次的最低水位所淹的桥的下标给予+1 -1的记数方法进行记数。最后对于计数数组进行处理
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn=100000+10; int q[maxn], c[maxn]; //q存储桥的高度, c用来记数 int main(){ // freopen("input.txt", "r", stdin); int n, m, k, i, t=1; while(~scanf("%d%d%d", &n, &m, &k) && (n||m||k)){ for(i=0; i<n; i++){
scanf("%d", &q[i]); }
sort(q, q+n); //对桥高度进行排序 memset(c, 0, sizeof(c)); int last=1; //用于记录水位上一次的最低点,初始为1 while(m--){ int high, lower; //水位高度 scanf("%d%d", &high, &lower); int l=upper_bound(q, q+n, last)-q; //找出比上一次低位高的桥的下标 int r=upper_bound(q, q+n, high)-q; //找出比高位高的桥的下标 c[l] +=1; //巧妙地记数~~~~ c[r] -=1; last = lower; } int ans=0, num=0; //ans记录当前下标桥的被淹次数,num满足条件的桥数 for(i=0; i<n; i++){ ans += c[i]; if(ans>=k){
num++;
} } printf("Case %d: %d\n", t++, num); } return 0; }

浙公网安备 33010602011771号