UVA - 10288 Coupons (数学 + 模拟)

本文介绍了一道算法题目UVA-10288,主要探讨了如何计算平均需要多少个谷物盒才能收集完整套编号从1到N的优惠券。文章提供了完整的AC代码,涵盖了输入输出格式、样例以及解题思路。

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

传送门:UVA - 10288

Coupons in cereal boxes are numbered 1 to n, and a set of one of each is required for a prize (a cereal box, of course). With one coupon per box, how many boxes on average are required to make a complete set of n coupons?

Input

Input consists of a sequence of lines each containing a single positive integer n, 1 ≤ n ≤ 33, giving the size of the set of coupons. Input is terminated by end of file.

Output

For each input line, output the average number of boxes required to collect the complete set of n coupons. If the answer is an integer number, output the number. If the answer is not integer, then output the integer part of the answer followed by a space and then by the proper fraction in the format shown below. The fractional part should be irreducible. There should be no trailing spaces in any line of output.

Sample Input

2

5

17

Sample Output

3

   5

11 --

   12

   340463

58 ------

   720720

题意:

谷物盒中的优惠券编号为1到N,每一个都需要一套奖品(谷物)。盒子,当然。每个盒子有一张优惠券,平均需要多少个盒子才能完成。

思路:

假设当前有k种谷物,那么获取新的谷物的概率(n-k)/n,所以需要步数的期望是n/(n-k).求和得到步数的期望是E(n)=n\sum_{i=1}^{n}\frac{1}{i}。需要注意的是n=1的时候需要特判一下,先把33以内的分母打表(方便运算)。

AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
ll gcd(ll a,ll b){return b ? gcd(b,a % b) : a;}
ll lcm(ll a,ll b){return a / gcd(a,b) * b;}
ll get_lenth(ll n)
{
    ll pos = 0;
    if(n == 0) return 1;
    while(n){
        n /= 10;
        pos++;
    }
    return pos;
}
ll fm_map[34];
void get_map()
{
    fm_map[1] = 1;
    for(int i = 2;i < 34;++i) fm_map[i] = lcm(fm_map[i - 1],i);
}
int main()
{
    ios::sync_with_stdio(0);
    ll n;
    get_map();
    while(cin >> n){
        ll cnt = 0,pos,tmp = n,fm = fm_map[n],fs = fm;
        for(int i = n - 1;i > 0;--i){
            tmp = fm / i * n + fs;
            cnt += tmp / fm;
            fs = tmp % fm;
        }
        pos = gcd(fs,fm);
        fs /= pos;fm /= pos;
        if(fs && cnt){
            ll len = get_lenth(cnt);
            for(int i = 0;i <= len;++i) cout << ' ';
            cout << fs << endl;
            len = get_lenth(fm);
            cout << cnt << ' ';
            for(int i = 0;i < len;++i) cout << '-';
            cout << endl;
            len = get_lenth(cnt);
            for(int i = 0;i <= len;++i) cout << ' ';
            cout << fm << endl;
        }
        else cout << (cnt ? cnt : cnt + 1) << endl;
    }
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值