kmjp's blog

競技プログラミング参加記です

yukicoder : No.2199 lower_bound and upper_bound

ちょっと言い換えるとわかりやすくなる問題。
https://yukicoder.me/problems/no/2199

問題

以下を満たすN要素の整数列Aは何通りか。

  • A[i]は-1以上の整数
  • sum(A)はL以上
  • Aのprefixの和はU以下

解法

B[i]=A[i]+1
と置くと、

  • B[i]は非負整数
  • sum(B)は(L+N)以上
  • Bのn要素の和は(U+n)以下

となる。sum(B)を総当たりすると、グリッド上(0,0)から(N,sum(B))まで右または上に隣接する格子点をたどる問題となる。
ただし、(n,U+n-1)を通っていはいけない。
これはカタラン数の数え方の応用で解くことができる。

int N,L,U;
const ll mo=998244353;

ll comb(ll N_, ll C_) {
	const int NUM_=1400001;
	static ll fact[NUM_+1],factr[NUM_+1],inv[NUM_+1];
	if (fact[0]==0) {
		inv[1]=fact[0]=factr[0]=1;
		for (int i=2;i<=NUM_;++i) inv[i] = inv[mo % i] * (mo - mo / i) % mo;
		for (int i=1;i<=NUM_;++i) fact[i]=fact[i-1]*i%mo, factr[i]=factr[i-1]*inv[i]%mo;
	}
	if(C_<0 || C_>N_) return 0;
	return factr[C_]*fact[N_]%mo*factr[N_-C_]%mo;
}

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>N>>L>>U;
	
	ll ret=0;
	for(x=L+N;x<=U+N;x++) {
		if(x<=U+1) ret+=comb(x+N-1,x);
		else ret+=comb(x+N-1,x)-comb(x+N-1,x-(U+2));
	}
	cout<<(ret%mo+mo)%mo<<endl;
}

まとめ

面倒な-1をさっさと消すのがコツ。