codeforces 816 B. Karen and Coffee(思维)

题目链接:http://codeforces.com/contest/816/problem/B

题意:给出n个范围,q个查询问查询区间出现多少点在给出的n个范围中至少占了k次

题解:很显然的一道题目,可能会想到用莫队,或者分块来写,但是这样会超时。这题有个技巧,可以考虑用前缀和来求。

首先在n个范围中给出了l,r,用一个数组a[],a[l]++,a[r+1]--,然后求前缀表示前i个有多少个超过k的。然后就简单了,具体看一下代码。

总而言之想法很重要。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int M = 2e5 + 10;
int a[M] , have[M];
int main() {
    int n , k , q;
    scanf("%d%d%d" , &n , &k , &q);
    for(int i = 0 ; i < n ; i++) {
        int l , r;
        scanf("%d%d" , &l , &r);
        a[l]++;
        a[r + 1]--;
    }
    have[0] = 0;
    int pre = 0;
    for(int i = 0 ; i < M ; i++) {
        pre += a[i];
        if(i) have[i] = have[i - 1];
        if(pre >= k) {
            have[i]++;
        }
    }
    for(int i = 0 ; i < q ; i++) {
        int l , r;
        scanf("%d%d" , &l , &r);
        printf("%d
" , have[r] - have[l - 1]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/TnT2333333/p/7050444.html