Skip to content

Commit e2bb175

Browse files
Create 切木头.md
1 parent 3d7b2b3 commit e2bb175

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Dichotomy/切木头.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#### 问题描述
2+
3+
给定长度为n的数组,每个元素代表一个木头的长度,木头可以任意截断,从这堆木头中截出至少k个相同长度为m的木块。已知k,求max(m)。
4+
5+
输入两行,第一行n, k,第二行为数组序列。输出最大值。数据保证有解,即结果至少是1。
6+
7+
**输入**
8+
9+
```
10+
5 5
11+
4 7 2 10 5
12+
```
13+
14+
**输出**
15+
16+
```
17+
4
18+
```
19+
20+
**解释**
21+
22+
如图,最多可以把它分成5段长度为4的木头
23+
24+
![](https://raw.githubusercontent.com/CompetitiveLin/ImageHostingService/picgo/imgs/202409211952291.png)
25+
26+
---
27+
28+
对结果二分:从一到木棍最长的长度进行二分遍历,每次遍历的长度作为 `i`,检查是否可以将所有木头截出来 `k` 个长度为 `i` 的木块
29+
30+
```go
31+
package main
32+
33+
import "fmt"
34+
35+
func main() {
36+
n, k := 5, 5
37+
arrays := []int{4, 7, 2, 10, 5}
38+
fmt.Println(wood(n, k, arrays))
39+
}
40+
41+
func check(arrays []int, m int) int {
42+
res := 0
43+
for i := range arrays {
44+
res += arrays[i] / m
45+
}
46+
return res
47+
}
48+
49+
func wood(n, k int, arrays []int) int {
50+
l, r := 1, 1
51+
for i := range arrays {
52+
if r < arrays[i] {
53+
r = arrays[i]
54+
}
55+
}
56+
r++
57+
for l < r {
58+
mid := (l + r + 1) >> 1
59+
if check(arrays, mid) >= k {
60+
l = mid
61+
} else {
62+
r = mid - 1
63+
}
64+
}
65+
return l
66+
}
67+
68+
```
69+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy