您的位置:首页 > 其它

CodeForces 689E (离散化+逆元+组合)

2016-07-12 15:23 246 查看
题意:给你n个闭区间,挑选k个区间并且把它们做交集,得到区间[L,R],定义f([L,R])=R-L+1;求所有可能的f值得和。

题解:

①当区间[L,R]出现的次数d>=k,则ans=C(n,k)*(R-L+1)

②数据比较大,需要把端点离散化,离散化时需把右端点+1,

③求组合需要用到除法,需把除法变为乘法,则要用到逆元,即a/b等于a*(b的逆元)

④求各个离散化后区间的f,并把它累加起来。

注意:中间过程防止爆int,鄙人经常爆,然后找BUG。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

#define maxn 200010
#define mod 1000000007

long long f[maxn];
int l[maxn];
int r[maxn];
int hash[maxn*2];
int res[maxn*2];

void fac()
{
f[0]=1;
for(int i=1;i<maxn;i++)
f[i]=(f[i-1]*i)%mod;
}

int qpow(long long x,int k)
{
long long res=1;
while(k)
{
if(k&1) res = res * x % mod;
x= x * x % mod;
k>>=1;
}
return res;
}

int inv(long long x)
{
return qpow(x,mod-2);
}

long long C(int n,int m)
{
return f
*inv(f[m]*f[n-m]%mod)%mod;
}

int main()
{
fac();
int n,k;
scanf("%d%d",&n,&k);
int cnt=0;
for(int i=0;i<n;i++)
{
scanf("%d%d",&l[i],&r[i]);
hash[cnt++]=l[i];
hash[cnt++]=++r[i];
}
sort(hash,hash+cnt);
cnt=unique(hash,hash+cnt)-hash;
for(int i=0;i<n;i++)
{
int temp=lower_bound(hash,hash+cnt,l[i])-hash;
res[temp]++;
temp=lower_bound(hash,hash+cnt,r[i])-hash;
res[temp]--;
}
int ans=0;
int add=res[0];
for(int i=1;i<cnt;i++)
{
if(add>=k) ans=(ans+C(add,k)*(hash[i]-hash[i-1])%mod)%mod;
add+=res[i];
}
printf("%d\n", ans);
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: