A. Packets (cf 1037 A) - Manthan, Codefest 18 (rated, Div. 1 + Div. 2)

本文介绍了一种算法,用于解决将n个相同价值的金币分配到若干个包裹中,使得能够通过选择不同组合的包裹得到从1到n的所有整数值。采用二进制优化的多重背包方法,将金币数量分解为接近log2x份,实现高效组合。

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

A. Packets
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You have n
coins, each of the same value of 1
Distribute them into packets such that any amount x
(1≤x≤n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, however it may be reused for the formation of other x’s.
Find the minimum number of packets in such a distribution.
Input
The only line contains a single integer n
(1≤n≤10^9 ) — the number of coins you have.
Output

Output a single integer — the minimum possible number of packets, satisfying the condition above.
Examples
Input
Copy

6

Output
Copy

3

Input
Copy

2

Output
Copy

2

Note

In the first example, three packets with 1, 2 and 3 coins can be made to get any amount x (1≤x≤6).
To get 1use the packet with 1coin.
To get 2 use the packet with 2coins.
To get 3 use the packet with 3 coins.
To get 4 use packets with 1 and 3 coins.
To get 5 use packets with 2 and 3 coins
To get 6 use all packets.

In the second example, two packets with 1 and 1 coins can be made to get any amount x (1≤x≤2).

题意:给出n个金币,求最少可以将这些金币分成几个钱袋使得使用这些钱袋可以拼成1~n中的每一个数。

多重背包的二进制优化。
就是将数量x分成接近log2x份
然后这log2x份能组合成1..x内的所有数字。
从而将多重背包转化成01背包
1,2,4,8….贪心地选,然后不够的部分x-(1+2+4…)再作为一份就好

#include <bits/stdc++.h>
#define LL long long
using namespace std;
int n;
int main(){
    scanf("%d",&n);
    int now = 0,cnt = 0;
    for (int i = 1; ;i*=2){
        now+=i;
        if (now>n) {
            now-=i;
            break;
        }
        cnt++;
    }
    if (now<n) cnt++;
    printf("%d\n",cnt);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值