[ABC172E] NEQ 题解
UKE_Automation · · 题解
[ABC172E] NEQ 题解
Problem
求出满足以下要求的序列
- 长度为
N ; - 每个元素的范围是
[1,M] ; - 每个位置上
A,B 不相等; -
Solution
我们先考虑基本的错排问题:
错排问题指的是有
这是一个递推问题。将
第一步,考虑放下第
第二步,考虑放下第
- 将它放在
n 位置,此时剩下的n-1 个元素有D(n-2) 种方法。 - 将它不放在
n 位置,这时对于除n 外的n-1 个元素有D(n-1) 种方法。
综上,
边界为
接下来,这道题目与错排十分相似,我们借鉴上面的做法。
首先,确定序列
接下来我们考虑对于一个固定的
我们继续沿用
然而,由于我们此时的选数范围不只局限在
在放入第
所以再根据加法原理,答案应该是
递推求解即可,此时边界条件是
最后结果就是
Code
注意 long long。
#include <bits/stdc++.h>
#define int long long
using namespace std;
typedef long long LL;
const int Maxn = 2e6 + 5;
const int Mod = 1e9 + 7;
int n, m;
int d[Maxn];
int ans;
int A(int n, int m) {
int res = 1;
for(int i = n; i >= n - m + 1; i--) {
res = (res * i) % Mod;
}
return res;
}
signed main() {
ios::sync_with_stdio(0);
cin >> n >> m;
d[0] = 1, d[1] = m - n;
ans = A(m, n);
for(int i = 2; i <= n; i++) {
d[i] = ((m - n) * d[i - 1] % Mod + (i - 1) * (d[i - 2] + d[i - 1]) % Mod) % Mod;
}
ans = (ans * d[n]) % Mod;
cout << ans;
return 0;
}