D - Rescue Nibel!(差分+组合数学+思维)详解

https://codeforces.com/contest/1420/problem/D


题意:问有多少种方案可以满足一段时间里面有k盏灯亮着。

思路:首先把区间的问题转化到差分上去。考虑用差分代替区间。

然后看样例

5 2
1 3
2 4
3 5
4 6
5 7

发现很符合区间覆盖的贪心样子。按照左端点排序。然后用一个cnt变量表示枚举到当前l时候前面还有多少能选的,cnt+=差分,如果当前枚举到的点差分值为1,说明在前面还亮着的取C(cnt,k-1)个就是答案。枚举就好了。

代码在本地出现异常..交上去ac.如果哪位懂的话感谢指出。

“terminate called after throwing an instance of 'std::bad_alloc'”

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=3e5+100;
typedef long long ll;
using namespace std;
const int inf=0x3f3f3f3f;
const int mod=998244353;
ll fac[maxn];
ll p=mod;
struct node{
	ll x,c;
	bool operator<(const struct node &T)const{
		if(x==T.x) return c<T.c;
		return x<T.x;
	} 
};
vector<node>q;
//bool cmp(node A,node B)
//{
//	if(A.x==B.x) return A.c<B.c;
//	return A.x<B.x;
//}
ll quick(ll a,ll b){
    ll ans=1;
    while(b){
        if(b&1)ans=ans*a%p;
        a=a*a%p;
        b/=2;
    }
    return ans%p;
}
ll ccc(ll n,ll m){//求组合数
	if(m>n) return 0;
	return (fac[n] * quick(fac[m], p - 2) % p * quick(fac[n - m], p - 2) % p)%p ;
}
int main()
{
    cin.tie(0);std::ios::sync_with_stdio(false);
	//ccc(4,3);
	fac[0] = 1;
    for (ll i = 1; i <= maxn; i++){
            fac[i] = fac[i - 1] * i % p;
    }
    ll n,k;cin>>n>>k;
	for(ll i=1;i<=n;i++)
    {
    	ll l,r;cin>>l>>r;
    	q.push_back({l,1});
    	q.push_back({r+1,-1});
	}
	sort(q.begin(),q.end());
	ll cnt=0;ll res=0;//cnt表示当前枚举到的l前面还有多少个亮着的 
	for(auto i:q)
	{
		if(i.c==1) res=(res%mod+ccc(cnt,k-1)%mod)%mod;
		cnt+=i.c;
	}
	cout<<res<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/108802592