D. Count the Arrays,组合,Educational Codeforces Round 83 (Rated for Div. 2)
D. Count the Arrays,Educational Codeforces Round 83 (Rated for Div. 2)
http://codeforces.com/contest/1312/problem/D
Your task is to calculate the number of arrays such that:
each array contains n elements;
each element is an integer from 1 to m;
for each array, there is exactly one pair of equal elements;
for each array a, there exists an index i such that the array is strictly ascending before the i-th element and strictly descending after it (formally, it means that aj<aj+1, if j<i, and aj>aj+1, if j≥i).
思路:首先枚举第i位有最大数字j,则前i-1位有 C j − 1 i − 1 C_{j-1}^{i-1} Cj−1i−1种取法,然后后面有n-i个数字,他们都在剩下的j-i个数字中取,因为一旦数字选定,他们的位置就确定了,所以其中有一个数字应该与前i-1个数字中的一个相同,那么取法就有i-1种,再从剩下的j-i个数字中选n-i-1个数字即可,故总的取法数为 C j − 1 i − 1 ∗ ( i − 1 ) ∗ C j − i n − i − 1 C_{j-1}^{i-1}*(i-1)*C_{j-i}^{n-i-1} Cj−1i−1∗(i−1)∗Cj−in−i−1,化简后为 j − n + 2 ∗ . . . ∗ j − 1 ( i − 2 ) ! ( n − i − 1 ) ! \frac{j-n+2 *...*j-1}{(i-2)!(n-i-1)!} (i−2)!(n−i−1)!j−n+2∗...∗j−1,直接预处理出所有要用到的数字的逆元,然后可以发现分子分母都只和i或j有关,分别枚举i,j即可,注意i,j的取值范围
#include<bits/stdc++.h>
#define ll long long
#define MAXN 400005
using namespace std;
const long long MOL = 998244353 ;
long long inv[MAXN],fac[MAXN];
long long qpow(long long a, long long b, long long mod)//?a^b % mod
{
long long ans = 1;
a %= mod;
while(b)
{
if(b & 1)ans = a*ans%mod;
b >>= 1;
a = a*a%mod;
}
return ans;
}
inline void getInv(int k)
{
fac[0] = 1;
for(int i = 1;i <= k;++i)
fac[i] = fac[i-1] * i % MOL;
inv[k] = qpow(fac[k],MOL-2,MOL);
for(int i = k-1;i >= 0;--i)
inv[i] = inv[i+1] * (i+1) % MOL;
}
int main()
{
int n,m;
ll ans;
getInv(MAXN-5);
while(~scanf("%d%d",&n,&m))
{
ans = 0;
for(int i = n-1;i <= m;++i)
ans = (ans + fac[i-1] * inv[i-n+1]%MOL)%MOL;
ll tmp = 0;
for(int i = 2;i < n;++i)
tmp = (tmp+inv[i-2] * inv[n-i-1]%MOL)%MOL;
ans = ans * tmp %MOL;
printf("%lld\n",ans);
}
return 0;
}