leetcode-458-Poor Pigs
題目描述:
There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.
Answer this question, and write an algorithm for the follow-up general case.
Follow-up:
If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.
?
要完成的函數:
int poorPigs(int buckets, int minutesToDie, int minutesToTest)?
?
說明:
1、這其實是一道數學題,想明白了代碼不超過兩行。我不會說我連前面的1000個桶這道具體的題目都做錯的……直到看見答案才明白過來。
2、具體數字的題目,答案是5,不是8、也不是23、更不是250。具體解法如下:
假設有25個桶,我們只需要兩只豬。把25個桶放成5行5列,如下形狀:每個×代表一個水桶。
| ? | 0min | 15min | 30min | 45min | 60min |
| 0min | × | × | × | × | × |
| 15min | × | × | × | × | × |
| 30min | × | × | × | × | × |
| 45min | × | × | × | × | × |
| 60min | × | × | × | × | × |
?
?
?
?
?
?
第一只豬在0min喝下第一行的水,在15min喝下第二行的水,在30min喝下第三行的水,在45min喝下第四行的水。如果45min喝下60min出結果的時候,豬還沒say goodbye的話,那么毒必定在最后一行。
與此同時,第二只豬在0min喝下第一列的水,15min喝下第二列的水……類推。如果45min喝下60min出結果的時候,豬還在,那說明毒在最后一列。結合第一只豬的結果,說明毒在最后一行最后一列。
我們可以看出,一只豬可以判斷一個維度的信息,兩只豬可以決定兩個維度的信息,也就是5^2=25個水桶的情況可以由兩只豬判斷得出。
所以三只豬可以判斷5^3=125,四只豬可以判斷5^4=625,五只豬可以判斷5^5>1000個水桶的情況。
?
3、所以放到通用的題目里面,n個待判定的水桶,限時p分鐘,m分鐘出一次結果,這道題結果就是ceil(log(p/m+1)n),ceil是取上限函數。
代碼如下:
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {int chances=floor(minutesToTest/minutesToDie);return ceil(log10(buckets)/log10(chances+1));//變換一下底數,以10為底,結果一樣}上述代碼實測2ms,beats 100% of cpp submissions。大家做的都一樣。
轉載于:https://www.cnblogs.com/chenjx85/p/8930819.html
總結
以上是生活随笔為你收集整理的leetcode-458-Poor Pigs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP权限管理系统源码下载
- 下一篇: 性能测试监控工具nmon安装及使用方法