斯特林数的具体应用例题：

HDU 6143 Killer Names

HDU 3625 Examining the Rooms

我又来水博客了～

CONTENT

## HDU 6143 Killer Names

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 65536/65536 K (Java/Others)

### Problem Description

Galen Marek, codenamed Starkiller, was a male Human apprentice of the Sith Lord Darth Vader. A powerful Force-user who lived during the era of the Galactic Empire, Marek originated from the Wookiee home planet of Kashyyyk as the sole offspring of two Jedi Knights—Mallie and Kento Marek—who deserted the Jedi Order during the Clone Wars. Following the death of his mother, the young Marek's father was killed in battle by Darth Vader. Though only a child, Marek possessed an exceptionally strong connection to the Force that the Dark Lord of the Sith sought to exploit.

When Marek died in 2 BBY, shortly after the formation of the Alliance, Vader endeavored to recreate his disciple by utilizing the cloning technologies of the planet Kamino. The accelerated cloning process—an enhanced version of the Kaminoan method which allowed for a rapid growth rate within its subjects—was initially imperfect and many clones were too unstable to take Marek's place as the Dark Lord's new apprentice. After months of failure, one particular clone impressed Vader enough for him to hope that this version might become the first success. But as with the others, he inherited Marek's power and skills at the cost of receiving his emotions as well, a side effect of memory flashes used in the training process.

— Wookieepedia

Darth Vader is finally able to stably clone the most powerful soilder in the galaxy: the Starkiller. It is the time of the final strike to destroy the Jedi remnants hidden in every corner of the galaxy.

However, as the clone army is growing, giving them names becomes a trouble. A clone of Starkiller will be given a two-word name, a first name and a last name. Both the first name and the last name have exactly n characters, while each character is chosen from an alphabet of size m. It appears that there are m^{2n} possible names to be used.

Though the clone process succeeded, the moods of Starkiller clones seem not quite stable. Once an unsatisfactory name is given, a clone will become unstable and will try to fight against his own master. A name is safe if and only if no character appears in both the first name and the last name.

Since no two clones can share a name, Darth Vader would like to know the maximum number of clones he is able to create.

### Input

The First line of the input contains an integer T (T≤10), denoting the number of test cases.

Each test case contains two integers n and m (1≤n,m≤2000).

### Output

For each test case, output one line containing the maximum number of clones Vader can create.

Output the answer mod 10^9+7

### Sample Input

```
2
3 2
2 3
```

### Sample Output

```
2
18
```

### Translation

题目大意是，有 m 个字符，要你用这 m 个字符起名字，姓和名都是 n 个字符（每个字符从 m 个字符里选择），问你姓和名里的字母不能重复（也就是说姓里用了 i 字母，则名里不能用；反之亦然），有多少种起名方案。

### Solution

看到这种“有多少种方案”的题目，显然是排列组合、斯特林数有关的（至少是类似“放球DP”相关的）。

可以枚举左边（即姓）选了多少种字符，假设选了 i 个这些字符是姓里不能用的，那么剩下的就是 M-i 个字符。

先考虑右边：显然，右边 n 个字符，每个字符都可以取 M-i 里的任意一个，方案数是： (M-i)^N

再考虑左边：左边其实可以看成有 N 个位置，需要选择 i 个字符——这其实就是**第二类斯特林数**！N 个不同的小球，分到 i 个相同的盒子里，盒子可以为空。但是实际上盒子是不同的，所以再乘以 i! 即可。

最后的答案就是：

### Code

```
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=2005,tt=1e9+7;
int T,n,m,c[maxn][maxn],fac[maxn],f[maxn][maxn];
inline void Build(){
for (int i=0;i<=2000;i++) c[i][0]=1;
for (int i=1;i<=2000;i++){
c[i][0]=c[i][i]=1;
for (int j=1;j<i;j++) c[i][j]=(c[i-1][j]+c[i-1][j-1])%tt;
}
for (int i=1;i<=2000;i++) f[i][1]=1;
for (int i=2;i<=2000;i++)
for (int j=1;j<=i;j++)
f[i][j]=(f[i-1][j-1]+(long long)f[i-1][j]*j%tt)%tt;
fac[0]=1;
for (int i=1;i<=2000;i++) fac[i]=(long long)fac[i-1]*i%tt;
}
inline int qsm(int a,int b){
int ret=1,w=a;
while (b){
if (b&1) ret=(long long)ret*w%tt;
b>>=1;w=(long long)w*w%tt;
}
return ret;
}
int main(){
scanf("%d",&T);
Build();
while (T--){
scanf("%d%d",&n,&m);
int ans=0;
for (int i=1;i<m;i++) ans=((long long)ans+(long long)c[m][i]%tt*fac[i]%tt*f[n][i]%tt*qsm(m-i,n)%tt)%tt;
printf("%d\n",ans);
}
return 0;
}
```

## HDU 3625 Examining the Rooms

### Problem Description

A murder happened in the hotel. As the best detective in the town, you should examine all the N rooms of the hotel immediately. However, all the doors of the rooms are locked, and the keys are just locked in the rooms, what a trap! You know that there is exactly one key in each room, and all the possible distributions are of equal possibility. For example, if N = 3, there are 6 possible distributions, the possibility of each is 1/6. For convenience, we number the rooms from 1 to N, and the key for Room 1 is numbered Key 1, the key for Room 2 is Key 2, etc.

To examine all the rooms, you have to destroy some doors by force. But you don’t want to destroy too many, so you take the following strategy: At first, you have no keys in hand, so you randomly destroy a locked door, get into the room, examine it and fetch the key in it. Then maybe you can open another room with the new key, examine it and get the second key. Repeat this until you can’t open any new rooms. If there are still rooms un-examined, you have to randomly pick another unopened door to destroy by force, then repeat the procedure above, until all the rooms are examined.

Now you are only allowed to destroy at most K doors by force. What’s more, there lives a Very Important Person in Room 1. You are not allowed to destroy the doors of Room 1, that is, the only way to examine Room 1 is opening it with the corresponding key. You want to know what is the possibility of that you can examine all the rooms finally.

### Input

The first line of the input contains an integer T (T ≤ 200), indicating the number of test cases. Then T cases follow. Each case contains a line with two numbers N and K. (1 < N ≤ 20, 1 ≤ K < N)

### Output

Output one line for each case, indicating the corresponding possibility. Four digits after decimal point are preserved by rounding.

### Sample Input

```
3
3 1
3 2
4 2
```

### Sample Output

```
0.3333
0.6667
0.62500.3333 0.6667
```

### Hint

```
Sample Explanation
When N = 3, there are 6 possible distributions of keys:
Room 1 Room 2 Room 3 Destroy Times
#1 Key 1 Key 2 Key 3 Impossible
#2 Key 1 Key 3 Key 2 Impossible
#3 Key 2 Key 1 Key 3 Two
#4 Key 3 Key 2 Key 1 Two
#5 Key 2 Key 3 Key 1 One
#6 Key 3 Key 1 Key 2 One
In the first two distributions, because Key 1 is locked in Room 1 itself and you can’t destroy Room 1, it is impossible to open Room 1.
In the third and forth distributions, you have to destroy Room 2 and 3 both. In the last two distributions, you only need to destroy one of Room 2 or Room
```

### Translation

题目大意：有 N 个房间，现在你要检查所有房间。你可以暴力摧毁 K 扇门，但是第一个房间的门不能暴力破。每个房间里可能有其他房间的钥匙，问你最终可以检查所有房间的可能性（即概率）。

### Solution

先不考虑 1 号房间的“贵宾”，我们发现，其实是要把房间分成 t 个环（t ≤ k）。**环！环！环！第一类斯特林数！！！**

接下来考虑一下第一位贵宾的优待，我们只需要把破了第一位贵宾的门的情况全都减掉就可以了。总方案数就是：

最后问我们概率，只要除以全排列 N! 就可以了～

### Code

```
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=25;
int T,n,m;
long long f[maxn][maxn],fac[maxn];
inline void BuildFact(){
fac[0]=1;
for (int i=1;i<=20;i++) fac[i]=fac[i-1]*i;
}
inline void BuildStirlingNumber(){
f[1][1]=1;
for (int i=2;i<=20;i++)
for (int j=1;j<=i;j++)
f[i][j]=f[i-1][j-1]+(i-1)*f[i-1][j];
}
int main(){
BuildFact();
BuildStirlingNumber();
scanf("%d",&T);
while (T--){
scanf("%d%d",&n,&m);
long long now=0;
for (int i=1;i<=m;i++) now=now+f[n][i]-f[n-1][i-1];
printf("%.4f\n",(double)now/(double)fac[n]);
}
return 0;
}
```

本文章采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。

欢迎转载，如有错误欢迎指出。

本文链接：https://skywt.cn/posts/stirling-problems/