Codeforces 689E Mike and Geometry Problem(離散化+懶標記)

題意:給出n個線段[li,ri],求任意k個線段所共同覆蓋的點的總和。

解析:

對於每一條線段,區間[li,ri]加一,如果一個位置的值爲m,那麼最後的結果ans += C(m,k);

如果只是離散化端點的話,沒法求得中間部分被覆蓋的點,所以在離散化時保證相鄰兩點中間留出一個1,對於中間的點,求出當前的值*(相鄰兩點實際距離-1)即是結果。

[code]:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>

#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
using namespace std;
typedef long long LL;
const int maxn = 2e5+5;
const LL MOD = 1e9+7;

int mc[2*maxn],hah;
int n,m,L[maxn],R[maxn],C[4*maxn];
LL mul[maxn];

LL mod_pow(LL a,LL b,LL mod){
    LL res = 1;
    while(b){
        if(b&1) res=(res*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return res;
}

void init(){
    mul[0] = 1;hah = 0;
    for(int i = 1;i < maxn;i++) mul[i] = (i*mul[i-1])%MOD;
}

LL Comb(LL n,LL m,LL mod){ //C(n,m)%mod
    if(n<m) return 0;
    if(m==0||m==n) return 1;
    LL res=(mul[n]*mod_pow((mul[m]*mul[n-m])%mod,mod-2,mod))%mod;
    return res;
}

int main(){
    int i,j,cas;
    scanf("%d%d",&n,&m);
    init();
    for(i = 0;i < n;i++){
        scanf("%d%d",&L[i],&R[i]);
        mc[hah++] = L[i];
        mc[hah++] = R[i];
    }
    sort(mc,mc+hah);
    hah = unique(mc,mc+hah)-mc;

    for(i = 0;i < n;i++){
        int l,r;
        l = lower_bound(mc,mc+hah,L[i])-mc;
        r = lower_bound(mc,mc+hah,R[i])-mc;
        l *= 2;r *= 2;
        C[l]++;C[r+1]--;
    }
    LL ans = 0,sum = 0,tmp;
    for(i = 0;i < 2*hah;i++){
        sum += C[i];
        tmp = Comb(sum,m,MOD);
        if(i&1){
            ans = (ans + tmp*(mc[(i+1)/2]-mc[(i-1)/2]-1))%MOD;
        }else{
            ans = (ans+tmp)%MOD;
        }
    }
    printf("%I64d\n",ans);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章