Skip to content

Commit 1921fe9

Browse files
committed
改进写法
1 parent 2407e17 commit 1921fe9

File tree

1 file changed

+20
-29
lines changed
  • leetcode/season/2021fall/d

1 file changed

+20
-29
lines changed

leetcode/season/2021fall/d/d.go

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,46 @@
11
package main
22

3-
import (
4-
"sort"
5-
)
6-
7-
/* 二分+暴力枚举
8-
9-
注意到半径很小,我们可以枚举每个玩具,并暴力枚举该玩具**周围**是否有可以套住该玩具的圈。
10-
11-
具体来说,将 $\textit{circles}$ 排序后,将横坐标相同的圈分为一组。对每个玩具,可以套住该玩具的圈,在横坐标上,必然满足圈的最右端点不小于玩具的最右端点,且圈的最左端点不超过玩具的最左端点。对于纵坐标也是类似。这样我们可以二分要枚举的圈的初始位置,并向后遍历即可。
12-
13-
*/
3+
import "sort"
144

155
// github.com/EndlessCheng/codeforces-go
166
func circleGame(toys [][]int, circles [][]int, r0 int) (ans int) {
177
sort.Slice(circles, func(i, j int) bool { a, b := circles[i], circles[j]; return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] })
188

199
// 将横坐标相同的圈分为一组
20-
type pair struct{ x, y int }
21-
a, y := [][]pair{}, -1
10+
type pair struct {
11+
x int
12+
ys []int
13+
}
14+
a, y := []pair{}, -1
2215
for _, p := range circles {
23-
if len(a) == 0 || p[0] > a[len(a)-1][0].x {
24-
a = append(a, []pair{{p[0], p[1]}})
16+
if len(a) == 0 || p[0] > a[len(a)-1].x {
17+
a = append(a, pair{p[0], []int{p[1]}})
2518
y = -1
2619
} else if p[1] > y { // 去重
27-
a[len(a)-1] = append(a[len(a)-1], pair{p[0], p[1]})
20+
a[len(a)-1].ys = append(a[len(a)-1].ys, p[1])
2821
y = p[1]
2922
}
3023
}
3124

32-
outer:
3325
for _, t := range toys {
3426
x, y, r := t[0], t[1], t[2]
3527
if r > r0 {
3628
continue
3729
}
38-
i := sort.Search(len(a), func(i int) bool { return a[i][0].x+r0 >= x+r })
39-
for ; i < len(a); i++ {
40-
col := a[i]
41-
if col[0].x-r0 > x-r {
42-
break
43-
}
44-
j := sort.Search(len(col), func(j int) bool { return col[j].y+r0 >= y+r })
45-
for ; j < len(col); j++ {
46-
c := col[j]
47-
if c.y-r0 > y-r {
30+
i := sort.Search(len(a), func(i int) bool { return a[i].x+r0 >= x+r })
31+
for ; i < len(a) && a[i].x-r0 <= x-r; i++ {
32+
cx, ys := a[i].x, a[i].ys
33+
j := sort.SearchInts(ys, y)
34+
if j < len(ys) {
35+
if cy := ys[j]; (x-cx)*(x-cx)+(y-cy)*(y-cy) <= (r0-r)*(r0-r) {
36+
ans++
4837
break
4938
}
50-
if (x-c.x)*(x-c.x)+(y-c.y)*(y-c.y) <= (r0-r)*(r0-r) {
39+
}
40+
if j > 0 {
41+
if cy := ys[j-1]; (x-cx)*(x-cx)+(y-cy)*(y-cy) <= (r0-r)*(r0-r) {
5142
ans++
52-
continue outer
43+
break
5344
}
5445
}
5546
}

0 commit comments

Comments
 (0)