UVa12024 - Hats(错排问题)

本文讨论了John Hatman解决皇家伦敦剧院观众拿错帽子问题的方法,通过错排递推关系式和排列的递推式计算错排个数与排列总数的比例,并提供了具体的编程实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Background

John Hatman, the honest cloakroom attendant of the RoyalTheatre of London, would like to know the solution to the followingproblem.

TheProblem

Whenthe show finishes, all spectators in the theatre are in a hurry to see the Final of the UEFAChampionship. So, they run to the cloakroom to take their hats back.

Some of them take a wrong hat. But, how likely is thateveryone take a wrong hat?

TheInput

The first lineof the input contains an integer, t,indicating the number of test cases. For each test case, one lineappears, that contains anumber n, 2<=n<=12,representing the number of people and hats.

TheOutput

For each test case, the output should contain asingle line with the number representing the number of favourable cases(i.e., the number of cases where all people take a wrong hat),followed by a bar, "/", and followed by a number representing thetotal number of possible cases.

SampleInput

3
2
3
4

SampleOutput

1/2
2/6
9/24
题意 :求错排个数与排列的个数之比

思路:错排递推关系式为f(n) = (n-1)(f(n - 2) + f(n - 1)),排列的递推式为d(n) = n * d(n -1)

#include <cstdio>

using namespace std;

const int MAXN = 13;

typedef long long LL;

LL f[MAXN], fact[MAXN];
int n;

void init()
{
    f[0] = 0; f[1] = 0; f[2] = 1;
    fact[1] = 1; fact[2] = 2;
    
    for (int i = 3; i < MAXN; i++) {
        f[i] = (i - 1) * (f[i - 2] + f[i - 1]);
        fact[i] = i * fact[i - 1];
    }
}

void input()
{
    scanf("%d", &n);
}

void solve()
{
    printf("%d/%d\n", f[n], fact[n]);
}

int main(int argc, char **argv) 
{
#ifndef ONLINE_JUDGE
    freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif
    
    init();
    
    int cas;
    scanf("%d", &cas);
    while (cas--) {
        input();
        solve();
    }
    
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值