# # Leetcode 第248场周赛题解

## # Problem A - 基于排列构建数组 (opens new window)

### # 方法一：模拟

• 时间复杂度$\mathcal{O}(N)$
• 空间复杂度$\mathcal{O}(N)$

class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[x] for x in nums]

1
2
3

## # Problem B - 消灭怪物的最大数量 (opens new window)

### # 方法一：贪心

• 时间复杂度$\mathcal{O}(N\log N)$
• 空间复杂度$\mathcal{O}(N)$

class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
t = [(d - 1) // s for d, s in zip(dist, speed)]
t.sort()
for i in range(len(t)):
if t[i] < i:
return i
return len(t)

1
2
3
4
5
6
7
8

## # Problem C - 统计好数字的数目 (opens new window)

### # 方法一：数学

$5^{\left\lfloor\frac{n+1}{2}\right\rfloor}\cdot4^{\left\lfloor\frac{n}{2}\right\rfloor}$

• 时间复杂度$\mathcal{O}(\log N)$
• 空间复杂度$\mathcal{O}(1)$

class Solution:
def countGoodNumbers(self, n: int) -> int:
return pow(5, (n + 1) // 2, 1000000007) * pow(4, n // 2, 1000000007) % 1000000007

1
2
3

## # Problem D - 最长公共子路径 (opens new window)

### # 方法一：Rabin-Karp算法+二分答案

• 时间复杂度$\mathcal{O}(K\log\min len_i)$。其中$K$为所有数组的长度之和。
• 空间复杂度$\mathcal{O}(K)$

use std::collections::{HashSet, HashMap};

const MOD: u128 = 180143985094819841;
const K: u128 = 100019;

fn check(mid: usize, paths: &Vec<Vec<i32>>) -> bool {
let m = paths.len();
let mut f = 1;
for i in 0..mid {
f = f * K % MOD;
}
let mut cnt: HashMap<u128, usize> = HashMap::new();

for j in 0..m {
let mut now = 0u128;
let mut s: HashSet<u128> = HashSet::new();

for i in 0..paths[j].len() {
now = now * K + paths[j][i] as u128;
now %= MOD;

if i >= mid {
now = (now + MOD - paths[j][i - mid] as u128 * f % MOD) % MOD;
}

if i >= mid - 1 {
s.insert(now);
}
}

for &si in s.iter() {
*cnt.entry(si).or_insert(0) += 1;
}
}

for (_, &freq) in cnt.iter() {
if freq == m {
return true;
}
}

false
}

impl Solution {
pub fn longest_common_subpath(n: i32, paths: Vec<Vec<i32>>) -> i32 {
let m = paths.len();
let mut hi = paths.iter().map(|x| x.len()).min().unwrap();
let mut lo = 1;

while lo <= hi {
let mid = (lo + hi) >> 1;

if check(mid, &paths) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}

hi as i32
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

### # 方法二：后缀数组+二分答案

• 时间复杂度$\mathcal{O}(K\log\min len_i)$。其中$K$为所有数组的长度之和。这里二分答案的复杂度占主导。这里使用的求后缀数组和LCP数组的时间复杂度为线性复杂度。
• 空间复杂度$\mathcal{O}(K)$

use std::collections::HashSet;

fn sa_is(s: &[usize], upper: usize) -> Vec<usize> {
let n = s.len();
match n {
0 => return vec![],
1 => return vec![0],
2 => return if s[0] < s[1] { vec![0, 1] } else { vec![1, 0] },
_ => (),
}
let mut sa = vec![0; n];
let mut ls = vec![false; n];
for i in (0..n - 1).rev() {
ls[i] = if s[i] == s[i + 1] {
ls[i + 1]
} else {
s[i] < s[i + 1]
};
}
let mut sum_l = vec![0; upper + 1];
let mut sum_s = vec![0; upper + 1];
for i in 0..n {
if !ls[i] {
sum_s[s[i]] += 1;
} else {
sum_l[s[i] + 1] += 1;
}
}
for i in 0..=upper {
sum_s[i] += sum_l[i];
if i < upper {
sum_l[i + 1] += sum_s[i];
}
}

// sa's origin is 1.
let induce = |sa: &mut [usize], lms: &[usize]| {
for elem in sa.iter_mut() {
*elem = 0;
}
let mut buf = sum_s.clone();
for &d in lms {
if d == n {
continue;
}
let old = buf[s[d]];
buf[s[d]] += 1;
sa[old] = d + 1;
}
buf.copy_from_slice(&sum_l);
let old = buf[s[n - 1]];
buf[s[n - 1]] += 1;
sa[old] = n;
for i in 0..n {
let v = sa[i];
if v >= 2 && !ls[v - 2] {
let old = buf[s[v - 2]];
buf[s[v - 2]] += 1;
sa[old] = v - 1;
}
}
buf.copy_from_slice(&sum_l);
for i in (0..n).rev() {
let v = sa[i];
if v >= 2 && ls[v - 2] {
buf[s[v - 2] + 1] -= 1;
sa[buf[s[v - 2] + 1]] = v - 1;
}
}
};
// origin: 1
let mut lms_map = vec![0; n + 1];
let mut m = 0;
for i in 1..n {
if !ls[i - 1] && ls[i] {
lms_map[i] = m + 1;
m += 1;
}
}
let mut lms = Vec::with_capacity(m);
for i in 1..n {
if !ls[i - 1] && ls[i] {
lms.push(i);
}
}
assert_eq!(lms.len(), m);
induce(&mut sa, &lms);

if m > 0 {
let mut sorted_lms = Vec::with_capacity(m);
for &v in &sa {
if lms_map[v - 1] != 0 {
sorted_lms.push(v - 1);
}
}
let mut rec_s = vec![0; m];
let mut rec_upper = 0;
rec_s[lms_map[sorted_lms[0]] - 1] = 0;
for i in 1..m {
let mut l = sorted_lms[i - 1];
let mut r = sorted_lms[i];
let end_l = if lms_map[l] < m { lms[lms_map[l]] } else { n };
let end_r = if lms_map[r] < m { lms[lms_map[r]] } else { n };
let same = if end_l - l != end_r - r {
false
} else {
while l < end_l {
if s[l] != s[r] {
break;
}
l += 1;
r += 1;
}
l != n && s[l] == s[r]
};
if !same {
rec_upper += 1;
}
rec_s[lms_map[sorted_lms[i]] - 1] = rec_upper;
}

let rec_sa = sa_is(&rec_s, rec_upper);
for i in 0..m {
sorted_lms[i] = lms[rec_sa[i]];
}
induce(&mut sa, &mut sorted_lms);
}
for elem in sa.iter_mut() {
*elem -= 1;
}
sa
}

fn sa_is_i32(s: &[i32], upper: i32) -> Vec<usize> {
let s: Vec<usize> = s.iter().map(|&x| x as usize).collect();
sa_is(&s, upper as usize)
}

fn suffix_array(s: &[i32], upper: i32) -> Vec<usize> {
assert!(upper >= 0);
for &elem in s {
assert!(0 <= elem && elem <= upper);
}
sa_is_i32(s, upper)
}

fn lcp_array<T: Ord>(s: &[T], sa: &[usize]) -> Vec<usize> {
let n = s.len();
assert!(n >= 1);
let mut rnk = vec![0; n];
for i in 0..n {
rnk[sa[i]] = i;
}
let mut lcp = vec![0; n - 1];
let mut h = 0;
for i in 0..n - 1 {
if h > 0 {
h -= 1;
}
if rnk[i] == 0 {
continue;
}
let j = sa[rnk[i] - 1];
while j + h < n && i + h < n {
if s[j + h] != s[i + h] {
break;
}
h += 1;
}
lcp[rnk[i] - 1] = h;
}
lcp
}

impl Solution {
pub fn longest_common_subpath(n: i32, paths: Vec<Vec<i32>>) -> i32 {
let m = paths.len();
let mut hi = paths.iter().map(|x| x.len()).min().unwrap();
let mut lo = 1;

let mut global_path = vec![];
let mut belong = vec![];
let mut sep = n;
for path in paths.iter() {
for &city in path.iter() {
global_path.push(city);
belong.push(sep - n);
}
global_path.push(sep);
belong.push(sep - n);
sep += 1;
}

// sa[i] 表示排名为 i 的是哪一个后缀
let sa = suffix_array(&global_path, sep - 1);

// lcp[i] 表示排第 i 名和第 i+1 名的后缀的最长公共前缀的长度
let lcp = lcp_array(&global_path, &sa);

// 二分答案
while lo <= hi {
let mid = (lo + hi) >> 1;
let mut i = 0;
let mut found = false;
let mut vis = HashSet::new();

while i < lcp.len() {
if lcp[i] >= mid {
let mut j = i;
while j < lcp.len() && lcp[j] >= mid {
vis.insert(belong[sa[j]]);
j += 1;
}
vis.insert(belong[sa[j]]);

if vis.len() == m {
found = true;
break;
}

i = j;
vis.clear();
} else {
i += 1;
}
}

if found {
lo = mid + 1;
} else {
hi = mid - 1;
}
}

hi as i32
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237