[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
问题描述
你有一架天平。现在你要设计一套砝码,使得利用这些砝码可以称出任意 小于等于 NN 的正整数重量。
那么这套砝码最少需要包含多少个砝码?
注意砝码可以放在天平两边。
输入格式
输入包含一个正整数 N。
输出格式
输出一个整数代表答案。
样例输入
7
样例输出
3
样例说明
33 个砝码重量是 1、4、61、4、6,可以称出 11 至 77的所有重量。
1 = 1;1=1;
2 = 6 − 42=6−4(天平一边放 66,另一边放 44);
3 = 4 − 1;3=4−1;
4 = 4;4=4;
5 = 6 − 1;5=6−1;
6 = 6;6=6;
7 = 1 + 6;7=1+6;
少于 33 个砝码不可能称出 11 至 77 的所有重量。
评测用例规模与约定
对于所有评测用例,1 ≤ N ≤ 10000000001≤N≤1000000000。
运行限制
* 最大运行时间:1s
* 最大运行内存: 512M import java.util.Scanner; public class Main { public static
void main(String[] args) { Scanner scan = new Scanner(System.in); int N =
scan.nextInt(); scan.close(); //从砝码本身出发(从解出发去找解的角度) //一个砝码-只有N=1的情况
//二个砝码-只有N=2-4的情况 1 3-1 3 3+1 //三个砝码-只有N=5-13的情况 // [ (3^(n-1)-1)/2 + 1 ,
(3^n-1)/ 2 ] 规律区间 int n = 1; if (N != 1) { while (true) { if
((Math.pow(3,n-1)-1)/2 <= N && N <= (Math.pow(3,n)-1)/2) { break; } n++; } }
System.out.println(n); } }
题解思路
1、首先从问题下手,会发现若针对题给的砝码数量进行思考,要尝试多次递归,或是枚举,这会导致题目十分复杂,对N很大时复杂度难以想象;
2、接着看向题解,会发现,若从这个题解下手,是有规可循的。
比如这里 n = 1 时,称出重量结果必为 N = 1(n为最小砝码数量);
若 n = 2 时,称出重量结果必为 N = 2 ~ 4;
(1 3-1 3 3+1至N=4,N=2~3的情况易得)
若 n = 3 时,称出的重量结果必为 N = 5 ~ 13;
(N = 5的情况是因为砝码为2个时不够,故为3个的左区间)
3、对此从题解中得出规律,只要N在某个区间内,就可以很容易地得出n,即
4、最后用一个while循环或for循环遍历一下即可。