problemscpp
A collection of my answers to algorithm problems in c++.
leetcode.cpp
浏览该文件的文档.
1#include "leetcode.h"
2#include "templates.h"
3#include <algorithm>
4#include <bit>
5#include <bitset>
6#include <climits>
7#include <cmath>
8#include <cstring>
9#include <numeric>
10#include <queue>
11#include <regex>
12#include <sstream>
13#include <stack>
14#include <unordered_set>
15
16using namespace std;
17
18namespace leetcode {
19 bool TreeNode::operator==(const TreeNode &node) const {
20 if(this->left != nullptr && node.left == nullptr) {
21 return false;
22 }
23 if(this->left == nullptr && node.left != nullptr) {
24 return false;
25 }
26 if(this->right != nullptr && node.right == nullptr) {
27 return false;
28 }
29 if(this->right == nullptr && node.right != nullptr) {
30 return false;
31 }
32 if(this->left != nullptr && node.left != nullptr && *this->left != *node.left) {
33 return false;
34 }
35 if(this->right != nullptr && node.right != nullptr && *this->right != *node.right) {
36 return false;
37 }
38 return this->val == node.val;
39 }
40
41 bool TreeNode::operator!=(const TreeNode &node) const { return !(*this == node); }
42
43 namespace concatenated_words {
44 vector<string> Solution::findAllConcatenatedWordsInADict(vector<string> &words) {
45 sort(words.begin(), words.end(), [&](const string &a, const string &b) { return a.size() < b.size(); });
46 auto ans = vector<string>();
47 auto node = TrieNode(0);
48 for(const string &word: words) {
49 if(word.length() == 0) {
50 continue;
51 }
52 if(node.dfs(&node, word, 0, false)) {
53 ans.push_back(word);
54 } else {
55 node.insert(word);
56 }
57 }
58 return ans;
59 }
60
62 this->ch = ch;
63 this->is_end = false;
64 }
65
66 void TrieNode::insert(const string &str) {
67 auto *node = this->nexts[str[0] - 'a'];
68 if(node == nullptr) {
69 node = new TrieNode(str[0]);
70 this->nexts[str[0] - 'a'] = node;
71 }
72 if(str.length() == 1) {
73 node->is_end = true;
74 return;
75 }
76 return node->insert(str.substr(1));
77 }
78
79 bool TrieNode::dfs(TrieNode *root, const string &str, int start, bool flag) const {
80 if(this->ch == 0) {
81 //根节点
82 const auto *const node = this->nexts[str[start] - 'a'];
83 if(node == nullptr) {
84 return false;
85 }
86 return node->dfs(root, str, start, flag);
87 }
88 //非根节点
89 //到一个单词结束处
90 if(this->is_end) {
91 if(start == str.length() - 1) {
92 return flag;
93 }
94 const auto res = root->dfs(root, str, start + 1, true);
95 if(res) {
96 return true;
97 }
98 }
99 const TrieNode *node = nullptr;
100 if(str[start + 1] - 'a' >= 0) {
101 node = this->nexts[str[start + 1] - 'a'];
102 }
103 return node != nullptr && node->dfs(root, str, start + 1, flag);
104 }
105 }// namespace concatenated_words
106
107 namespace excel_sheet_column_number {
108 int Solution::titleToNumber(const std::string &columnTitle) {
109 int sum = 0;
110 int length = static_cast<int>(columnTitle.length());
111 for(const char c: columnTitle) {
112 sum += static_cast<int>(static_cast<double>(c - 'A' + 1) * pow(26, length-- - 1));
113 }
114 return sum;
115 }
116 }// namespace excel_sheet_column_number
117
118 namespace excel_sheet_column_title {
119 string Solution::convertToTitle(int columnNumber) {
120 auto ans = string();
121 bool round = false;
122 while(columnNumber != 0) {
123 char ch = 0;
124 if(round) {
125 ch = static_cast<char>(columnNumber % 26 + 63);
126 round = false;
127 } else {
128 ch = static_cast<char>(columnNumber % 26 + 64);
129 }
130 if(ch == '@' && columnNumber >= 26) {
131 ch = 'Z';
132 round = true;
133 } else if(ch == '?' && columnNumber >= 26) {
134 ch = 'Y';
135 round = true;
136 }
137 if('A' <= ch && ch <= 'Z') {
138 ans.insert(0, 1, ch);
139 }
140 columnNumber /= 26;
141 }
142 return ans;
143 }
144 }// namespace excel_sheet_column_title
145
146 namespace majority_element {
147 Solution::Solution() { this->m = std::map<int, int>(); }
148
149 int Solution::majorityElement(vector<int> &nums) {
150 for(int i: nums) {
151 if(m.contains(i)) {
152 m[i] = m[i] + 1;
153 if(m[i] > nums.size() / 2) {
154 return i;
155 }
156 } else {
157 m[i] = 1;
158 }
159 }
160 return 0;
161 }
162 }// namespace majority_element
163
164 namespace count_special_quadruplets {
165 int Solution::countQuadruplets(vector<int> &nums) {
166 int sum = 0;
167 for(int i = 3; i < nums.size(); i++) {
168 for(int j = 0; j < i - 2; j++) {
169 if(j == i) {
170 continue;
171 }
172 for(int k = j + 1; k < i - 1; k++) {
173 if(k == i) {
174 continue;
175 }
176 for(int l = k + 1; l < i; l++) {
177 if(l == i) {
178 continue;
179 }
180 if(nums[k] + nums[j] + nums[l] == nums[i]) {
181 sum++;
182 }
183 }
184 }
185 }
186 }
187 return sum;
188 }
189 }// namespace count_special_quadruplets
190
191 namespace hand_of_straights {
192 bool Solution::isNStraightHand(vector<int> &hand, int groupSize) {
193 if(hand.size() % groupSize != 0) {
194 return false;
195 }
196 if(groupSize == 1) {
197 return true;
198 }
199 sort(hand.begin(), hand.end());
200 const auto len = hand.size() / groupSize;
201 for(int i = 0; i < len; i++) {
202 int current = *hand.begin();
203 hand.erase(hand.begin());
204 for(int j = 1; j < groupSize; j++) {
205 auto next = find(hand.begin(), hand.end(), current + 1);
206 if(next == hand.end()) {
207 return false;
208 }
209 current = *next;
210 hand.erase(next);
211 }
212 }
213 return true;
214 }
215 }// namespace hand_of_straights
216
217 namespace perfect_number {
219 int sum = 0;
220 int max = num;
221 for(int i = 1; i < max; i++) {
222 if(num % i == 0) {
223 sum += i;
224 if(i != 1) {
225 sum += num / i;
226 }
227 max = num / i;
228 }
229 }
230 return sum == num;
231 }
232 }// namespace perfect_number
233
234 namespace convert_bst_to_greater_tree {
236 if(root == nullptr) {
237 return nullptr;
238 }
239 FriendTreeNode *sum = copy(root);
240 get_sum(sum);
241 sum->val = sum->sum - (sum->left == nullptr ? 0 : sum->left->sum);
242 convert(sum);
243 return root;
244 }
245
247 auto *ret = new FriendTreeNode(node->val, node);
248 if(node->left != nullptr) {
249 ret->left = copy(node->left);
250 }
251 if(node->right != nullptr) {
252 ret->right = copy(node->right);
253 }
254 return ret;
255 }
256
258 if(node->left != nullptr) {
259 get_sum(node->left);
260 node->sum += node->left->sum;
261 }
262 if(node->right != nullptr) {
263 get_sum(node->right);
264 node->sum += node->right->sum;
265 }
266 }
267
269 if(sum_node->right != nullptr) {
270 sum_node->right->val = sum_node->val - sum_node->friend_node->val -
271 (sum_node->right->left == nullptr ? 0 : sum_node->right->left->sum);
272 convert(sum_node->right);
273 }
274 if(sum_node->left != nullptr) {
275 sum_node->left->val = sum_node->val + sum_node->left->friend_node->val +
276 (sum_node->left->right == nullptr ? 0 : sum_node->left->right->sum);
277 convert(sum_node->left);
278 }
279 sum_node->friend_node->val = sum_node->val;
280 }
281 }// namespace convert_bst_to_greater_tree
282
283 namespace convert_1d_array_into_2d_array {
284 vector<vector<int>> Solution::construct2DArray(vector<int> &original, int m, int n) {
285 if(original.size() != static_cast<unsigned long long>(m) * static_cast<unsigned long long>(n)) {
286 return {};
287 }
288 auto ans = vector<vector<int>>();
289 int count = 0;
290 for(int i = 0; i < m; i++) {
291 auto row = vector<int>();
292 for(int j = 0; j < n; j++) {
293 row.push_back(original[count++]);
294 }
295 ans.push_back(row);
296 }
297 return ans;
298 }
299 }// namespace convert_1d_array_into_2d_array
300
301 namespace elimination_game {
303 int num_amount = n;
304 int loop_cnt = 0;
305 int a0 = 1;//初项
306 int d = 1;//差
307 while(num_amount != 1) {
308 //剩下的数目不为1时
309 if(num_amount % 2 == 1) {
310 // 奇数个数字
311 a0 = a0 + d;
312 } else if(num_amount % 2 == 0) {
313 // 偶数个数字
314 const bool left_to_right = loop_cnt % 2 == 0;
315 if(left_to_right) {
316 a0 = a0 + d;
317 } else {
318 a0 = a0;
319 }
320 }
321 loop_cnt++;
322 d *= 2;
323 num_amount /= 2;
324 }
325 return a0;
326 }
327 }// namespace elimination_game
328
329 namespace check_if_all_as_appears_before_all_bs {
330 bool Solution::checkString(const string &s) {
331 bool flag = true;
332 for(const char ch: s) {
333 if(ch == 'a') {
334 if(!flag) {
335 return false;
336 }
337 } else if(ch == 'b') {
338 flag = false;
339 }
340 }
341 return true;
342 }
343 }// namespace check_if_all_as_appears_before_all_bs
344
345 namespace number_of_laser_beams_in_a_bank {
346 int Solution::numberOfBeams(vector<string> &bank) {
347 if(bank.size() == 1) {
348 return 0;
349 }
350 int count = 0;
351 int i = 0;
352 int count_i = deviceCount(bank[i]);
353 int j = 1;
354 while(i < j && i < bank.size() && j < bank.size()) {
355 if(deviceCount(bank[j]) == 0) {
356 j++;
357 continue;
358 }
359 const int count_j = deviceCount(bank[j]);
360 count += count_i * count_j;
361 count_i = count_j;
362 i = j;
363 j++;
364 }
365 return count;
366 }
367
368 int Solution::deviceCount(const string &str) {
369 int count = 0;
370 for(const char c: str) {
371 if(c == '1') {
372 count++;
373 }
374 }
375 return count;
376 }
377 }// namespace number_of_laser_beams_in_a_bank
378
379 namespace destroying_asteroids {
380 bool Solution::asteroidsDestroyed(int mass, vector<int> &asteroids) {
381 long long m = mass;
382 sort(asteroids.begin(), asteroids.end());
383 for(const int i: asteroids) {
384 if(m < i) {
385 return false;
386 }
387 m += i;
388 }
389 return true;
390 }
391 }// namespace destroying_asteroids
392
393 /*namespace maximum_employees_to_be_invited_to_a_meeting {
394 int Solution::maximumInvitations(vector<int>& favorite) {
395 int n = static_cast<int>(favorite.size());
396 vector<vector<int >> g(n), rg(n); // rg 为图 g 的反图
397 vector<int> deg(n); // 图 g 上每个节点的入度
398 for (int v = 0; v < n; ++v) {
399 int w = favorite[v];
400 g[v].emplace_back(w);
401 rg[w].emplace_back(v);
402 ++deg[w];
403 }
404
405 // 拓扑排序,剪掉图 g 上的所有树枝
406 queue<int> q;
407 for (int i = 0; i < n; ++i) {
408 if (deg[i] == 0) {
409 q.emplace(i);
410 }
411 }
412 while (!q.empty()) {
413 int v = q.front();
414 q.pop();
415 for (int w : g[v]) {
416 if (--deg[w] == 0) {
417 q.emplace(w);
418 }
419 }
420 }
421
422 // 寻找图 g 上的基环
423 vector<int> ring;
424 vector<int> vis(n);
425
426 function<void(int)> dfs = [&](int v) {
427 vis[v] = true;
428 ring.emplace_back(v);
429 for (int w : g[v]) {
430 if (!vis[w]) {
431 dfs(w);
432 }
433 }
434 };
435
436 // 通过反图 rg 寻找树枝上最深的链
437 int max_depth = 0;
438
439 function<void(int, int, int)> rdfs = [&](int v, int fa, int depth) {
440 max_depth = max(max_depth, depth);
441 for (int w : rg[v]) {
442 if (w != fa) {
443 rdfs(w, v, depth + 1);
444 }
445 }
446 };
447
448 int max_ring_size = 0, sum_chian_size = 0;
449 for (int i = 0; i < n; ++i) {
450 if (!vis[i] && deg[i]) { // 遍历基环上的点(拓扑排序后入度不为 0)
451 ring.resize(0);
452 dfs(i);
453 int sz = static_cast<int>(ring.size());
454 if (sz == 2) { // 基环大小为 2
455 int v = ring[0], w = ring[1];
456 max_depth = 0;
457 rdfs(v, w, 1);
458 sum_chian_size += max_depth; // 累加 v 这一侧的最长链的长度
459 max_depth = 0;
460 rdfs(w, v, 1);
461 sum_chian_size += max_depth; // 累加 w 这一侧的最长链的长度
462 }
463 else {
464 max_ring_size = max(max_ring_size, sz); // 取所有基环的最大值
465 }
466 }
467 }
468 return max(max_ring_size, sum_chian_size);
469 }
470 }*/
474 namespace day_of_the_week {
475 string Solution::dayOfTheWeek(int day, int month, int year) {
476 const string output[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
477 const int dayofmonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
478 int count = 5;
479 count += (year - 1971) * 365;
480 count += (year - 1) / 4 - 1970 / 4;
481 for(int m = 0; m < month - 1; m++) {
482 count += dayofmonths[m];
483 }
484 if(month > 2 && year % 4 == 0 && year % 100 != 0) {
485 count++;
486 }
487 count += day - 1;
488 count %= 7;
489 return output[count];
490 }
491 }// namespace day_of_the_week
492
493 namespace cat_and_mouse {
494 int Solution::catMouseGame(vector<vector<int>> &graph) {
495 this->n = graph.size();
496 this->graph = graph;
497 memset(dp, -1, sizeof dp);
498 return getResult(1, 2, 0);
499 }
500
501 int Solution::getResult(int mouse, int cat, int turns) {
502 if(turns == n * 2) {
503 return DRAW;
504 }
505 if(dp[mouse][cat][turns] < 0) {
506 if(mouse == 0) {
507 dp[mouse][cat][turns] = MOUSE_WIN;
508 } else if(cat == mouse) {
509 dp[mouse][cat][turns] = CAT_WIN;
510 } else {
511 getNextResult(mouse, cat, turns);
512 }
513 }
514 return dp[mouse][cat][turns];
515 }
516
517 void Solution::getNextResult(int mouse, int cat, int turns) {
518 const int curMove = turns % 2 == 0 ? mouse : cat;
519 const int defaultResult = curMove == mouse ? CAT_WIN : MOUSE_WIN;
520 int result = defaultResult;
521 for(int next: graph[curMove]) {
522 if(curMove == cat && next == 0) {
523 continue;
524 }
525 const int nextMouse = curMove == mouse ? next : mouse;
526 const int nextCat = curMove == cat ? next : cat;
527 const int nextResult = getResult(nextMouse, nextCat, turns + 1);
528 if(nextResult != defaultResult) {
529 result = nextResult;
530 if(result != DRAW) {
531 break;
532 }
533 }
534 }
535 dp[mouse][cat][turns] = result;
536 }
537 }// namespace cat_and_mouse
538
539 namespace replace_all_s_to_avoid_consecutive_repeating_characters {
540 string Solution::modifyString(string s) {
541 for(int i = 0; i < s.size(); i++) {
542 if(s[i] == '?') {
543 for(char ch = 'a'; ch < 'z' + 1; ch++) {
544 if(0 <= i - 1 && s[i - 1] == ch) {
545 continue;
546 }
547 if(i + 1 < s.size() && s[i + 1] == ch) {
548 continue;
549 }
550 s[i] = ch;
551 break;
552 }
553 }
554 }
555 return s;
556 }
557 }// namespace replace_all_s_to_avoid_consecutive_repeating_characters
558
559 namespace simplify_path {
560 string Solution::simplifyPath(const string &path) {
561 auto *const str_cpy = new char[path.size() + 1];
562 memcpy(str_cpy, path.c_str(), path.size() + 1);
563 auto *next = strtok(str_cpy, "/");
564 auto stck = deque<string>();
565 while(next != nullptr) {
566 auto nextstr = string(next);
567 if(nextstr == "..") {
568 if(!stck.empty()) {
569 stck.pop_back();
570 }
571 next = strtok(nullptr, "/");
572 continue;
573 }
574 if(nextstr == ".") {
575 next = strtok(nullptr, "/");
576 continue;
577 }
578 stck.emplace_back(next);
579 next = strtok(nullptr, "/");
580 }
581 auto oss = ostringstream();
582 if(stck.empty()) {
583 oss << '/';
584 } else {
585 while(!stck.empty()) {
586 auto pname = stck.front();
587 oss << '/' << pname;
588 stck.pop_front();
589 }
590 }
591 delete[] str_cpy;
592 return oss.str();
593 }
594 }// namespace simplify_path
595
596 namespace maximum_nesting_depth_of_the_parentheses {
597 int Solution::maxDepth(const string &s) {
598 int max = 0;
599 int current = 0;
600 for(const char ch: s) {
601 if(ch == '(') {
602 current++;
603 } else if(ch == ')') {
604 current--;
605 }
606 if(max < current) {
607 max = current;
608 }
609 }
610 return max;
611 }
612 }// namespace maximum_nesting_depth_of_the_parentheses
613
614 namespace gray_code {
615 vector<int> Solution::grayCode(int n) {
616 vector<int> ret(1 << n);
617 for(int i = 0; i < ret.size(); i++) {
618 ret[i] = i >> 1 ^ i;
619 }
620 return ret;
621 }
622 }// namespace gray_code
623
624 namespace check_if_every_row_and_column_contains_all_numbers {
625 bool Solution::checkValid(vector<vector<int>> &matrix) {
626 const unsigned int n = matrix.size();
627 for(int i = 0; i < n; i++) {
628 auto *const row = new bool[n + 1];
629 memset(row, 1, (n + 1) * sizeof(bool));
630 for(int j = 0; j < n; j++) {
631 if(!row[matrix[i][j]]) {
632 delete[] row;
633 return false;
634 }
635 row[matrix[i][j]] = false;
636 }
637 delete[] row;
638 }
639
640 for(int j = 0; j < n; j++) {
641 auto *const column = new bool[n + 1];
642 memset(column, 1, (n + 1) * sizeof(bool));
643 for(int i = 0; i < n; i++) {
644 if(!column[matrix[i][j]]) {
645 delete[] column;
646 return false;
647 }
648 column[matrix[i][j]] = false;
649 }
650 delete[] column;
651 }
652 return true;
653 }
654 }// namespace check_if_every_row_and_column_contains_all_numbers
655
656 namespace minimum_swaps_to_group_all_1s_together_ii {
657 int Solution::minSwaps(vector<int> &nums) {
658 int onecount = 0;
659 for(const int num: nums) {
660 if(num == 1) {
661 onecount++;
662 }
663 }
664 if(onecount == 0) {
665 return 0;
666 }
667
668 int zerocount = 0;
669 for(int i = 0; i < onecount; i++) {
670 if(nums[i] == 0) {
671 zerocount++;
672 }
673 }
674 int min = zerocount;
675
676 for(int i = 0; i < nums.size(); i++) {
677 if(nums[i] == 0) {
678 zerocount--;
679 }
680 if(nums[(onecount + i) % nums.size()] == 0) {
681 zerocount++;
682 }
683 if(zerocount < min) {
684 min = zerocount;
685 }
686 }
687 return min;
688 }
689 }// namespace minimum_swaps_to_group_all_1s_together_ii
690
691 namespace count_words_obtained_after_adding_a_letter {
692 int Solution::wordCount(vector<string> &startWords,
693 vector<string> &targetWords) {
694 int count = 0;
695 auto start = unordered_set<unsigned int>();
696 for(const string &word: startWords) {
697 auto bin = str2bin(word);
698 start.insert(bin);
699 }
700 for(const string &word: targetWords) {
701 const auto bin = str2bin(word);
702 for(int i = 0; i < 26; i++) {
703 if((bin & 1 << i) != 0 && start.contains(bin - (1 << i))) {
704 //bin有第i个字母且bin去掉第i个字母在start中仍然存在
705 count++;
706 break;
707 }
708 }
709 }
710 return count;
711 }
712
713 unsigned int Solution::str2bin(const string &str) {
714 unsigned int ret = 0;
715 for(const char ch: str) {
716 ret |= 1 << ch - 'a';
717 }
718 return ret;
719 }
720 }// namespace count_words_obtained_after_adding_a_letter
721
722 namespace slowest_key {
723 char Solution::slowestKey(vector<int> &releaseTimes, string keysPressed) {
724 int max = releaseTimes[0];
725 int maxi = 0;
726 for(int i = 1; i < releaseTimes.size(); i++) {
727 const int time = releaseTimes[i] - releaseTimes[i - 1];
728 if(max < time) {
729 max = time;
730 maxi = i;
731 } else if(max == time) {
732 if(keysPressed[i] > keysPressed[maxi]) {
733 maxi = i;
734 }
735 }
736 }
737 return keysPressed[maxi];
738 }
739 }// namespace slowest_key
740
741 namespace additive_number {
742 bool Solution::isAdditiveNumber(string num) {
743 if(num.length() < 3) {
744 return false;
745 }
746 auto *const nums = new char[num.length()];
747 for(int i = 0; i < num.length(); i++) {
748 nums[i] = num[i];
749 }
750 for(int i = 1; i <= num.length() - i; i++) {
751 const auto n1 = str2ui(nums, 0, i);
752 for(int j = i + 1; j - i <= num.length() - j; j++) {
753 const auto n2 = str2ui(nums, i, j - i);
754 if(dfs(n1, n2, nums, num.length(), j)) {
755 return true;
756 }
757 if(n2 == 0) {
758 break;
759 }
760 }
761 if(n1 == 0) {
762 break;
763 }
764 }
765 delete[] nums;
766 return false;
767 }
768
769 bool Solution::dfs(unsigned long long n1, unsigned long long n2, const char *nums, unsigned short length, unsigned short current) {
770 const auto sum = to_string(n1 + n2);
771 if(sum.length() > length - current) {
772 //前两位和的位数超过剩余的位数
773 return false;
774 }
775 if(!equal(sum, nums, current, length)) {
776 //不包含下一个数字
777 return false;
778 }
779 if(current + sum.length() == length) {
780 //终止条件
781 return true;
782 }
783 const auto n3 = str2ui(nums, current, sum.length());
784 return dfs(n2, n3, nums, length, current + sum.length());
785 }
786
787 unsigned long long Solution::str2ui(const char *str, unsigned short start, unsigned short length) {
788 unsigned long long ans = 0;
789 for(int i = start; i < start + length; i++) {
790 ans *= 10;
791 ans += str[i] - '0';
792 }
793 return ans;
794 }
795
796 bool Solution::equal(string sum, const char *nums, unsigned short start, unsigned short length) {
797 int j = 0;
798 for(int i = start; j < sum.length() && i < length; i++, j++) {
799 if(sum[j] != nums[i]) {
800 return false;
801 }
802 }
803 return j == sum.length();
804 }
805 }// namespace additive_number
806
807 namespace decode_the_slanted_ciphertext {
808 string Solution::decodeCiphertext(string encodedText, int rows) {
809 if(encodedText.empty()) {
810 return "";
811 }
812 const int columns = encodedText.length() / rows;
813 auto *const table = new char *[rows];
814 for(int i = 0; i < rows; i++) {
815 table[i] = new char[columns - rows + 2];
816 for(int j = i; j - i < columns - rows + 2; j++) {
817 if(i * columns + j < encodedText.length()) {
818 table[i][j - i] = encodedText[i * columns + j];
819 } else {
820 table[i][j - i] = ' ';
821 }
822 }
823 }
824 auto oss = ostringstream();
825 for(int j = 0; j < columns - rows + 2; j++) {
826 for(int i = 0; i < rows; i++) {
827 oss << table[i][j];
828 }
829 }
830 string ans = oss.str();
831 for(int i = 0; i < rows; i++) {
832 delete[] table[i];
833 }
834 delete[] table;
835 return rtrim(ans);
836 }
837
838 string Solution::rtrim(string &s) {
839 for(int i = s.length() - 1; i >= 0; i--) {
840 if(s[i] != ' ') {
841 string ans = s.substr(0, i + 1);
842 return ans;
843 }
844 }
845 return s;
846 }
847 }// namespace decode_the_slanted_ciphertext
848
849 namespace escape_a_large_maze {
850 bool Solution::isEscapePossible(vector<vector<int>> &blocked, vector<int> &source, vector<int> &target) {
851 const int limit = blocked.size() * (blocked.size() - 1) / 2;
852 if(blocked.empty()) {
853 return true;
854 }
855 auto *p_source = new point(source[0], source[1], 0, nullptr);
856 auto *p_target = new point(target[0], target[1], 0, nullptr);
857 auto blocked_set_source = unordered_set<point, point_hash>();
858 auto blocked_set_target = unordered_set<point, point_hash>();
859 for(auto block: blocked) {
860 blocked_set_source.insert(point(block[0], block[1], 0, nullptr));
861 blocked_set_target.insert(point(block[0], block[1], 0, nullptr));
862 }
863 const unsigned int source_status = search(blocked_set_source, p_source, p_target, limit);
864 if(source_status == 0) {
865 return false;
866 }
867 if(source_status == 1) {
868 return true;
869 }
870 const unsigned int target_status = search(blocked_set_target, p_target, p_source, limit);
871 delete p_source;
872 delete p_target;
873 return target_status != 0;
874 }
875
876 unsigned int Solution::search(unordered_set<point, point_hash> &block_set, point *source, point *target, unsigned int limit) {
877 auto pq = priority_queue<point>();
878 pq.push(point(source->x, source->y, 0, target));
879 int count = 0;
880 while(!pq.empty()) {
881 if(count > limit || pq.size() > limit) {
882 return 2;//不包围
883 }
884 count++;
885 const auto p = pq.top();
886 pq.pop();
887 point nexts[] = {point(p.x + 1, p.y, p.distance + 1, target), point(p.x - 1, p.y, p.distance + 1, target), point(p.x, p.y + 1, p.distance + 1, target), point(p.x, p.y - 1, p.distance + 1, target)};
888 for(auto next: nexts) {
889 if(0 <= next.x && next.x < 1000000 && 0 <= next.y && next.y < 1000000 && !block_set.contains(next)) {
890 if(next.x == target->x && next.y == target->y) {
891 return 1;//连通
892 }
893 pq.push(next);
894 block_set.insert(next);
895 }
896 }
897 }
898 return 0;//不连通
899 }
900
901 bool point::operator<(const point &p) const { return this->distance + (abs(static_cast<int>(this->x - target->x)) + abs(static_cast<int>(this->y - target->y))) < p.distance + (abs(static_cast<int>(p.x - target->x)) + abs(static_cast<int>(p.y - target->y))); }
902 bool point::operator==(const point &p) const { return this->x == p.x && this->y == p.y; }
903
904 size_t point_hash::operator()(const point &p) const { return p.x * 1000000 + p.y; }
905 }// namespace escape_a_large_maze
906
907 namespace increasing_triplet_subsequence {
908 bool Solution::increasingTriplet(vector<int> &nums) {
909 if(nums.size() < 3) {
910 return false;
911 }
912 auto *min = new int[nums.size()];
913 auto *max = new int[nums.size()];
914 min[0] = nums[0];
915 max[nums.size() - 1] = nums[nums.size() - 1];
916 for(int i = 1, j = nums.size() - 2; i < nums.size() && j >= 0; i++, j--) {
917 if(min[i - 1] > nums[i]) {
918 min[i] = nums[i];
919 } else {
920 min[i] = min[i - 1];
921 }
922
923 if(max[j + 1] < nums[j]) {
924 max[j] = nums[j];
925 } else {
926 max[j] = max[j + 1];
927 }
928 }
929 for(int i = 0; i < nums.size(); i++) {
930 if(nums[i] > min[i] && nums[i] < max[i]) {
931 delete[] min;
932 delete[] max;
933 return true;
934 }
935 }
936 delete[] min;
937 delete[] max;
938 return false;
939 }
940 }// namespace increasing_triplet_subsequence
941
942 namespace largest_number_at_least_twice_of_others {
943 int Solution::dominantIndex(vector<int> &nums) {
944 if(nums.size() < 2) {
945 return 0;
946 }
947 unsigned int max;
948 unsigned int index;
949 unsigned int second;
950 if(nums[0] < nums[1]) {
951 max = nums[1];
952 index = 1;
953 second = nums[0];
954 } else {
955 max = nums[0];
956 index = 0;
957 second = nums[1];
958 }
959 for(int i = 2; i < nums.size(); i++) {
960 if(nums[i] > max) {
961 second = max;
962 index = i;
963 max = nums[i];
964 } else if(nums[i] > second) {
965 second = nums[i];
966 }
967 }
968 if(max >= 2 * second) {
969 return index;
970 }
971 return -1;
972 }
973 }// namespace largest_number_at_least_twice_of_others
974
975 namespace find_k_pairs_with_smallest_sums {
976 vector<vector<int>> Solution::kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k) {
977 auto ans = vector<vector<int>>();
978 auto pq = priority_queue<pair>();
979 for(int i = 0; i < k && i < nums1.size(); i++) {
980 for(int j = 0; j < k && j < nums2.size(); j++) {
981 pq.push(pair(nums1[i], nums2[j]));
982 }
983 }
984 for(int i = 0; i < k && i < nums1.size() * nums2.size(); i++) {
985 const pair p = pq.top();
986 pq.pop();
987 auto to_add = vector<int>();
988 to_add.resize(2);
989 to_add[0] = p.u;
990 to_add[1] = p.v;
991 ans.push_back(to_add);
992 }
993 return ans;
994 }
995
996 bool pair::operator<(const pair &p) const { return this->u + this->v > p.u + p.v; }
997 }// namespace find_k_pairs_with_smallest_sums
998
999 namespace permutations {
1000 vector<vector<int>> Solution::permute(vector<int> &nums) {
1001 auto ans = vector<vector<int>>();
1002 if(nums.size() == 1) {
1003 auto next_ans = vector<int>();
1004 next_ans.push_back(nums[0]);
1005 ans.push_back(next_ans);
1006 return ans;
1007 }
1008 for(auto num: nums) {
1009 auto next = vector(nums);
1010 next.erase(find(next.begin(), next.end(), num));
1011 auto next_permutations = permute(next);
1012 auto new_ans = vector<int>();
1013 new_ans.push_back(num);
1014 for(auto next_permutation: next_permutations) {
1015 auto next_ans = vector(new_ans);
1016 next_ans.insert(next_ans.end(), next_permutation.begin(), next_permutation.end());
1017 ans.push_back(next_ans);
1018 }
1019 }
1020 return ans;
1021 }
1022 }// namespace permutations
1023
1024 namespace calculate_money_in_leetcode_bank {
1026 int sum = n / 7 * (28 + 7 * (n / 7 + 3)) / 2;
1027 for(int i = 0; i < n % 7; i++) {
1028 sum += n / 7 + 1 + i;
1029 }
1030 return sum;
1031 }
1032 }// namespace calculate_money_in_leetcode_bank
1033
1034 namespace linked_list_random_node {
1036 int i = 1;
1037 int ans = 0;
1038 for(const auto *node = head; node != nullptr; node = node->next, i++) {
1039 if(rand() % i == 0) {
1040 // 1/i 的概率选中(替换为答案)
1041 ans = node->val;
1042 }
1043 }
1044 return ans;
1045 }
1046 }// namespace linked_list_random_node
1047
1048 namespace divide_a_string_into_groups_of_size_k {
1049 vector<string> Solution::divideString(const string &s, int k, char fill) {
1050 auto ans = vector<string>();
1051 int i = 0;
1052 for(; i * k + k < s.length(); i++) {
1053 ans.push_back(s.substr(i * k, k));
1054 }
1055 if(i * k != s.length()) {
1056 string last = s.substr(i * k);
1057 for(int j = last.length(); j < k; j++) {
1058 last += fill;
1059 }
1060 ans.push_back(last);
1061 }
1062 return ans;
1063 }
1064 }// namespace divide_a_string_into_groups_of_size_k
1065
1066 namespace minimum_moves_to_reach_target_score {
1067 int Solution::minMoves(int target, int maxDoubles) {
1068 int count = 0;
1069 while(target != 1) {
1070 if(maxDoubles == 0) {
1071 return count + target - 1;
1072 }
1073 if(target % 2 == 0 && maxDoubles != 0) {
1074 target /= 2;
1075 maxDoubles--;
1076 } else {
1077 target--;
1078 }
1079 count++;
1080 }
1081 return count;
1082 }
1083 }// namespace minimum_moves_to_reach_target_score
1084
1085 namespace solving_questions_with_brainpower {
1086 long long Solution::mostPoints(vector<vector<int>> &questions) {
1087 vector<long long> f(questions.size() + 1);
1088 for(int i = questions.size() - 1; i >= 0; --i) {
1089 auto &q = questions[i];
1090 const int j = i + q[1] + 1;
1091 f[i] = max(f[i + 1], q[0] + (j < questions.size() ? f[j] : 0));
1092 }
1093 return f[0];
1094 }
1095 }// namespace solving_questions_with_brainpower
1096
1097 namespace maximum_running_time_of_n_computers {
1098 long long Solution::maxRunTime(int n, vector<int> &batteries) {
1099 auto check = [&](long long t) {
1100 long long sum = 0;
1101 for(const int i: batteries) {
1102 sum += min(t, static_cast<long long>(i));
1103 }
1104 return sum / t >= n;
1105 };
1106
1107 long long l = 1;
1108 long long r = 1e16;
1109 while(l < r) {
1110 const long long m = (l + r) / 2;
1111 if(check(m)) {
1112 l = m + 1;
1113 } else {
1114 r = m;
1115 }
1116 }
1117 return l - 1;
1118 }
1119 }// namespace maximum_running_time_of_n_computers
1120
1121 namespace coun_vowels_permutation {
1124 unsigned long long end[5] = {1, 1, 1, 1, 1};
1125 for(int _i = 1; _i < n; _i++) {
1126 const unsigned long long a = (end[1] + end[2] + end[4]) % 1000000007;
1127 const unsigned long long e = (end[0] + end[2]) % 1000000007;
1128 const unsigned long long i = (end[1] + end[3]) % 1000000007;
1129 const unsigned long long o = end[2] % 1000000007;
1130 const unsigned long long u = (end[2] + end[3]) % 1000000007;
1131 end[0] = a;
1132 end[1] = e;
1133 end[2] = i;
1134 end[3] = o;
1135 end[4] = u;
1136 }
1137 return (end[0] + end[1] + end[2] + end[3] + end[4]) % 1000000007;
1138 }
1139 }// namespace coun_vowels_permutation
1140
1141 namespace minimum_time_difference {
1142 int Solution::findMinDifference(vector<string> &timePoints) {
1143 auto vec = vector<int>();
1144 for(string timePoint: timePoints) {
1145 vec.push_back(((timePoint[0] - '0') * 10 + (timePoint[1] - '0')) * 60 + (timePoint[3] - '0') * 10 + (timePoint[4] - '0'));
1146 }
1147 sort(vec.begin(), vec.end());
1148 int minimum = INT_MAX;
1149 for(int i = 0; i + 1 < vec.size(); i++) {
1150 minimum = min(minimum, vec[i + 1] - vec[i]);
1151 }
1152 minimum = min(minimum, vec[0] + 24 * 60 - vec[vec.size() - 1]);
1153 return minimum;
1154 }
1155 }// namespace minimum_time_difference
1156
1157 namespace contains_duplicate_ii {
1158 bool Solution::containsNearbyDuplicate(vector<int> &nums, int k) {
1159 auto um = unordered_map<int, vector<int>>();
1160 for(int i = 0; i < nums.size(); i++) {
1161 if(!um.contains(nums[i])) {
1162 um.insert(pair(nums[i], vector<int>()));
1163 }
1164 auto pos = lower_bound(um[nums[i]].begin(), um[nums[i]].end(), i);
1165 if(pos != um[nums[i]].end() && abs(*pos - i) <= k || pos != um[nums[i]].begin() && abs(*(pos - 1) - i) <= k) {
1166 return true;
1167 }
1168 um[nums[i]].insert(pos, i);
1169 }
1170 for(auto i: um) {
1171 sort(i.second.begin(), i.second.end());
1172 }
1173 return false;
1174 }
1175 }// namespace contains_duplicate_ii
1176
1177 namespace stone_game_ix {
1178 bool Solution::stoneGameIX(vector<int> &stones) {
1179 unsigned int remove = 0;
1180 unsigned int counts[3] = {0, 0, 0};
1181 for(auto stone: stones) {
1182 stone %= 3;
1183 counts[stone]++;
1184 }
1185 if(stones.size() == 1) {
1186 return false;
1187 }
1188 if(counts[1] + counts[2] == 2) {
1189 if(counts[1] == 2 || counts[2] == 2) {
1190 return false;
1191 }
1192 }
1193 if(counts[1] == 0 && counts[2] == 0) {
1194 return false;
1195 }
1196 if(abs(static_cast<int>(counts[1]) - static_cast<int>(counts[2])) <= 2) {
1197 return counts[0] % 2 == 0;
1198 }
1199 return true;
1200 }
1201 }// namespace stone_game_ix
1202
1203 namespace jump_game_iv {
1204 int Solution::minJumps(vector<int> &arr) {
1205 if(arr.size() == 1) {
1206 return 0;
1207 }
1208 auto pq = queue<pair<int, int>>();//<下标,step>
1209 auto *flag = new bool[arr.size()];
1210 memset(flag, 0, arr.size() * sizeof(bool));
1211 auto um = unordered_map<int, vector<int>>();//<值,下标>
1212 for(int i = 0; i < arr.size(); i++) {
1213 if(!um.contains(arr[i])) {
1214 auto vec = vector<int>();
1215 vec.push_back(i);
1216 um.insert(pair(arr[i], vec));
1217 } else {
1218 um[arr[i]].push_back(i);
1219 }
1220 }
1221 pq.push(pair(0, 0));
1222 flag[0] = true;
1223 while(!pq.empty()) {
1224 auto [current_i, current_count] = pq.front();
1225 pq.pop();
1226 if(current_i == arr.size() - 1) {
1227 return current_count;
1228 }
1229 if(um.contains(arr[current_i])) {
1230 for(auto i: um[arr[current_i]]) {
1231 if(i != current_i && !flag[i]) {
1232 pq.push(pair(i, current_count + 1));
1233 flag[i] = true;
1234 }
1235 }
1236 }
1237 um.erase(arr[current_i]);
1238 if(current_i - 1 >= 0 && !flag[current_i - 1]) {
1239 pq.push(pair(current_i - 1, current_count + 1));
1240 flag[current_i - 1] = true;
1241 }
1242 if(current_i + 1 < arr.size() && !flag[current_i + 1]) {
1243 pq.push(pair(current_i + 1, current_count + 1));
1244 flag[current_i + 1] = true;
1245 }
1246 }
1247 delete[] flag;
1248 return 0;
1249 }
1250 }// namespace jump_game_iv
1251
1252 namespace remove_palindromic_subsequences {
1254 for(int i = 0, j = s.length() - 1; i < j; i++, j--) {
1255 if(s[i] != s[j]) {
1256 return 2;
1257 }
1258 }
1259 return 1;
1260 }
1261 }// namespace remove_palindromic_subsequences
1262
1263 namespace UhWRSj {
1264 string Solution::replaceWords(vector<string> &dictionary, const string &sentence) {
1265 auto oss = ostringstream();
1266 auto *const nstr = new char[sentence.length() + 1];
1267 auto tn = TrieNode();
1268 for(const auto &root: dictionary) {
1269 tn.insert(root);
1270 }
1271 strcpy(nstr, sentence.c_str());
1272 char *word = strtok(nstr, " ");
1273 while(word != nullptr) {
1274 oss << tn.get_prefix("", string(word)) << " ";
1275 word = strtok(nullptr, " ");
1276 }
1277 const string ans = oss.str();
1278 delete[] nstr;
1279 return ans.substr(0, ans.length() - 1);
1280 }
1281
1282 void TrieNode::insert(const string &str) {
1283 if(str.empty()) {
1284 this->endroot = true;
1285 return;
1286 }
1287 if(this->next[str[0] - 'a'] == nullptr) {
1288 this->next[str[0] - 'a'] = new TrieNode(str[0]);
1289 }
1290 this->next[str[0] - 'a']->insert(str.substr(1));
1291 }
1292
1293 string TrieNode::get_prefix(string root, const string &str) const {
1294 if(this->endroot || str.empty()) {
1295 return root;
1296 }
1297 if(this->next[str[0] - 'a'] == nullptr) {
1298 return root + str;
1299 }
1300 return this->next[str[0] - 'a']->get_prefix(root + str[0], str.substr(1));
1301 }
1302 }// namespace UhWRSj
1303
1304 namespace minimum_cost_of_buying_candies_with_discount {
1305 int Solution::minimumCost(vector<int> &cost) {
1306 if(cost.size() == 1) {
1307 return cost[0];
1308 }
1309 if(cost.size() == 2) {
1310 return cost[0] + cost[1];
1311 }
1312 int count = 0;
1313 sort(cost.rbegin(), cost.rend());
1314 for(int i = 0; i < cost.size(); i++) {
1315 if(i % 3 != 2) {
1316 count += cost[i];
1317 }
1318 }
1319 return count;
1320 }
1321 }// namespace minimum_cost_of_buying_candies_with_discount
1322
1323 namespace count_the_hidden_sequences {
1324 int Solution::numberOfArrays(vector<int> &differences, int lower, int upper) {
1325 long long current = 0;
1326 long long maximum = 0;
1327 long long minimum = 0;
1328 for(const auto difference: differences) {
1329 current += difference;
1330 maximum = max(maximum, current);
1331 minimum = min(minimum, current);
1332 }
1333 return max(static_cast<long long>(0), upper - lower - (maximum - minimum) + 1);
1334 }
1335 }// namespace count_the_hidden_sequences
1336
1337 namespace k_highest_ranked_items_within_a_price_range {
1338 vector<vector<int>> Solution::highestRankedKItems(vector<vector<int>> &grid, vector<int> &pricing, vector<int> &start, int k) {
1339 const auto m = grid.size();
1340 const auto n = grid[0].size();
1341 auto ans = vector<vector<int>>();
1342 const auto low = pricing[0];
1343 const auto high = pricing[1];
1344 const auto row = start[0];
1345 const auto col = start[1];
1346 auto pq = priority_queue<item>();
1347 pq.push(item(0, grid[row][col], row, col));
1348 grid[row][col] = 0;
1349 while(pq.empty() && k != 0) {
1350 auto current = pq.top();
1351 pq.pop();
1352 if(current.price != 1 && current.price >= low && current.price <= high) {
1353 k--;
1354 auto vec = vector<int>();
1355 vec.push_back(current.row);
1356 vec.push_back(current.col);
1357 ans.push_back(vec);
1358 }
1359 pair<int, int> nexts[4] = {pair(current.row + 1, current.col),
1360 pair(current.row - 1, current.col),
1361 pair(current.row, current.col + 1),
1362 pair(current.row, current.col - 1)};
1363 for(const pair<int, int> next: nexts) {
1364 if(0 <= next.first && next.first < m && 0 <= next.second && next.second < n && grid[next.first][next.second] != 0) {
1365 pq.push(item(current.distance + 1, grid[next.first][next.second], next.first, next.second));
1366 grid[next.first][next.second] = 0;
1367 }
1368 }
1369 }
1370 return ans;
1371 }
1372
1373 bool item::operator<(const item &i) const {
1374 if(this->distance != i.distance) {
1375 return this->distance > i.distance;
1376 }
1377 if(this->price != i.price) {
1378 return this->price > i.price;
1379 }
1380 if(this->row != i.row) {
1381 return this->row > i.row;
1382 }
1383 return this->col > i.col;
1384 }
1385 }// namespace k_highest_ranked_items_within_a_price_range
1386
1387 namespace number_of_ways_to_divide_a_long_corridor {
1388 int Solution::numberOfWays(string corridor) {
1389 unsigned int s_count = 0;
1390 auto p = vector<unsigned int>();
1391 for(const char ch: corridor) {
1392 if(ch == 'S') {
1393 s_count++;
1394 }
1395 }
1396 if(s_count == 0 || s_count % 2 != 0) {
1397 return 0;
1398 }
1399 if(s_count == 2) {
1400 return 1;
1401 }
1402 unsigned int start = 0;
1403 unsigned int end = corridor.length() - 1;
1404 for(; start < end; start++) {
1405 if(corridor[start] == 'S') {
1406 break;
1407 }
1408 }
1409 for(; end > start; end--) {
1410 if(corridor[end] == 'S') {
1411 break;
1412 }
1413 }
1414 s_count = 1;
1415 unsigned int p_count = 0;
1416 bool flag = false;//是否在边界
1417 for(unsigned int i = start + 1; i <= end; i++) {
1418 if(corridor[i] == 'S') {
1419 s_count++;
1420 } else {
1421 if(s_count == 0) {
1422 p_count++;
1423 }
1424 }
1425 s_count %= 2;
1426 if(s_count == 0) {
1427 flag = true;
1428 } else if(s_count == 1) {
1429 if(flag) {
1430 p.push_back(p_count + 1);
1431 p_count = 0;
1432 }
1433 flag = false;
1434 }
1435 }
1436 unsigned long long ans = 1;
1437 for(const auto i: p) {
1438 ans *= i;
1439 ans %= 1000000007;
1440 }
1441 return ans;
1442 }
1443 }// namespace number_of_ways_to_divide_a_long_corridor
1444
1445 namespace count_elements_with_strictly_smaller_and_greater_elements {
1446 int Solution::countElements(vector<int> &nums) {
1447 int maximum = nums[0];
1448 int minimum = nums[0];
1449 for(auto num: nums) {
1450 maximum = max(maximum, num);
1451 minimum = min(minimum, num);
1452 }
1453 unsigned int count = 0;
1454 for(const auto num: nums) {
1455 if(maximum != num && minimum != num) {
1456 count++;
1457 }
1458 }
1459 return count;
1460 }
1461 }// namespace count_elements_with_strictly_smaller_and_greater_elements
1462
1463 namespace rearrange_array_elements_by_sign {
1464 vector<int> Solution::rearrangeArray(vector<int> &nums) {
1465 const auto size = nums.size();
1466 auto ans = vector<int>();
1467 auto positive = vector<int>();
1468 auto negative = vector<int>();
1469 for(auto num: nums) {
1470 if(num > 0) {
1471 positive.push_back(num);
1472 } else {
1473 negative.push_back(num);
1474 }
1475 }
1476 for(int i = 0; i < size / 2; i++) {
1477 ans.push_back(positive[i]);
1478 ans.push_back(negative[i]);
1479 }
1480 return ans;
1481 }
1482 }// namespace rearrange_array_elements_by_sign
1483
1484 namespace find_all_lonely_numbers_in_the_array {
1485 vector<int> Solution::findLonely(vector<int> &nums) {
1486 if(nums.size() == 1) {
1487 return nums;
1488 }
1489 sort(nums.begin(), nums.end());
1490 auto ans = vector<int>();
1491 if(nums[1] - nums[0] > 1) {
1492 ans.push_back(nums[0]);
1493 }
1494 if(nums[nums.size() - 1] - nums[nums.size() - 2] > 1) {
1495 ans.push_back(nums[nums.size() - 1]);
1496 }
1497 for(int i = 1; i < nums.size() - 1; i++) {
1498 if(nums[i] - nums[i - 1] > 1 && nums[i + 1] - nums[i] > 1) {
1499 ans.push_back(nums[i]);
1500 }
1501 }
1502 return ans;
1503 }
1504 }// namespace find_all_lonely_numbers_in_the_array
1505
1506 namespace maximum_good_people_based_on_statements {
1507 int Solution::maximumGood(vector<vector<int>> &statements) {
1508 int maximum = 0;
1509 auto dup = unordered_map<int, bool>();
1510 for(int i = 0; i < statements.size(); i++) {
1511 if(dup[i]) {
1512 continue;
1513 }
1514 const auto um = unordered_map<int, bool>();
1515 auto que = queue<msg>();
1516 que.push(msg(i, true));
1517 auto ans = dfs(statements, um, que);
1518 maximum = max(maximum, ans.first);
1519 for(auto it: ans.second) {
1520 if(it.second) {
1521 dup.insert(it);
1522 }
1523 }
1524 }
1525 return maximum;
1526 }
1527
1528 pair<int, unordered_map<int, bool>> Solution::dfs(vector<vector<int>> &statements, unordered_map<int, bool> um, queue<msg> que) {
1529 int maximum = 0;
1530 bool contradict = false;
1531 while(!que.empty()) {
1532 auto current = que.front();
1533 que.pop();
1534 if(um.contains(current.person)) {
1535 //已经存在
1536 if(um[current.person] != current.good) {
1537 //矛盾
1538 return pair<int, unordered_map<int, bool>>(0, {});
1539 }
1540 } else {
1541 um.insert(pair(current.person, current.good));
1542 }
1543 if(current.good) {
1544 //是好人
1545 for(int j = 0; j < statements.size(); j++) {
1546 if(statements[current.person][j] != 2 && j != current.person) {
1547 auto nmsg = msg(j, statements[current.person][j] == 1);
1548 if(um.contains(nmsg.person)) {
1549 //已经有了
1550 if(um[nmsg.person] != nmsg.good) {
1551 //矛盾
1552 contradict = true;
1553 return pair<int, unordered_map<int, bool>>(0, {});
1554 }
1555 } else {
1556 //还没有
1557 que.push(nmsg);
1558 }
1559 }
1560 }
1561 }
1562 }
1563 if(!contradict) {
1564 //不矛盾
1565 auto dup = unordered_map<int, bool>();
1566 for(int i = 0; i < statements.size(); i++) {
1567 if(dup[i]) {
1568 continue;
1569 }
1570 if(!um.contains(i)) {
1571 bool all2 = true;
1572 for(auto v: statements[i]) {
1573 if(v != 2) {
1574 all2 = false;
1575 }
1576 }
1577 if(all2) {
1578 um.insert(pair(i, true));
1579 continue;
1580 }
1581 auto nque = queue<msg>();
1582 nque.push(msg(i, true));
1583 auto ans = dfs(statements, um, nque);
1584 maximum = max(maximum, ans.first);
1585 for(auto it: ans.second) {
1586 if(it.second) {
1587 dup.insert(it);
1588 }
1589 }
1590 }
1591 }
1592
1593 int good_count = 0;
1594 for(auto i: um) {
1595 if(i.second) {
1596 good_count++;
1597 }
1598 }
1599 maximum = max(maximum, good_count);
1600 }
1601 return pair(maximum, um);
1602 }
1603 }// namespace maximum_good_people_based_on_statements
1604
1605 namespace stock_price_fluctuation {
1607 ms = multiset<int>();
1608 m = map<int, int>();
1609 }
1610
1611 void StockPrice::update(int timestamp, int price) {
1612 if(!m.contains(timestamp)) {
1613 m.insert(pair(timestamp, price));
1614 } else {
1615 ms.erase(ms.find(m[timestamp]));
1616 m[timestamp] = price;
1617 }
1618 ms.insert(price);
1619 }
1620
1621 int StockPrice::current() const { return (*m.rbegin()).second; }
1622
1623 int StockPrice::maximum() const { return *ms.rbegin(); }
1624
1625 int StockPrice::minimum() const { return *ms.begin(); }
1626 }// namespace stock_price_fluctuation
1627
1628 namespace second_minimum_time_to_reach_destination {
1629 int Solution::secondMinimum(int n, vector<vector<int>> &edges, int time, int change) {
1630 auto record = unordered_map<int, vector<int>>();
1631 for(int i = 1; i <= n; i++) {
1632 record.insert(pair(i, vector<int>()));
1633 }
1634 auto um = unordered_map<int, unordered_set<int>>();
1635 for(auto edge: edges) {
1636 if(!um.contains(edge[0])) {
1637 auto us = unordered_set<int>();
1638 us.insert(edge[1]);
1639 um.insert(pair(edge[0], us));
1640 } else {
1641 um[edge[0]].insert(edge[1]);
1642 }
1643 if(!um.contains(edge[1])) {
1644 auto us = unordered_set<int>();
1645 us.insert(edge[0]);
1646 um.insert(pair(edge[1], us));
1647 } else {
1648 um[edge[1]].insert(edge[0]);
1649 }
1650 }
1651 auto pq = priority_queue<status>();
1652 pq.push(status(1, 0));
1653 bool flag = false;//已经到达一次终点
1654 int prev = 0;
1655 while(!pq.empty()) {
1656 status current = pq.top();
1657 pq.pop();
1658 if(current.position == n) {
1659 if(!flag) {
1660 flag = true;
1661 prev = current.time;
1662 } else {
1663 if(current.time != prev) {
1664 return current.time;
1665 }
1666 }
1667 }
1668
1669 if(record[current.position].empty() || record[current.position].size() == 1 && current.time != *record[current.position].rbegin()) {
1670 //可以继续
1671 record[current.position].push_back(current.time);
1672 } else {
1673 continue;
1674 }
1675
1676 for(int next: um[current.position]) {
1677 int next_time;
1678 if(current.time / change % 2 == 1) {
1679 //当前为红灯
1680 next_time = (current.time / change + 1) * change + time;
1681 } else {
1682 next_time = current.time + time;
1683 }
1684 auto next_status = status(next, next_time);
1685 if(record[next_status.position].empty() || record[next_status.position].size() == 1 && next_status.time != *record[next_status.position].rbegin()) {
1686 //可以继续
1687 pq.push(next_status);
1688 }
1689 }
1690 }
1691 return 0;
1692 }
1693
1694 bool status::operator<(const status &s) const { return this->time > s.time; }
1695 }// namespace second_minimum_time_to_reach_destination
1696
1697 namespace count_of_matches_in_tournament {
1698 int Solution::numberOfMatches(int n) { return n - 1; }
1699 }// namespace count_of_matches_in_tournament
1700
1701 namespace detect_squares {
1702 DetectSquares::DetectSquares() { ms = multiset<pair<int, int>>(); }
1703
1704 void DetectSquares::add(vector<int> point) { ms.insert(pair(point[0], point[1])); }
1705
1706 int DetectSquares::count(vector<int> point) const {
1707 int count = 0;
1708 for(auto p: ms) {
1709 if(p.first != point[0] && p.second != point[1] && abs(p.first - point[0]) == abs(p.second - point[1])) {
1710 count += ms.count(pair(p.first, point[1])) * ms.count(pair(point[0], p.second));
1711 }
1712 }
1713 return count;
1714 }
1715 }// namespace detect_squares
1716
1717 namespace number_of_valid_words_in_a_sentence {
1718 int Solution::countValidWords(const string &sentence) {
1719 auto *str = new char[sentence.length() + 1];
1720 strcpy(str, sentence.c_str());
1721 int count = 0;
1722 for(const char *token = strtok(str, " "); token != nullptr; token = strtok(nullptr, " ")) {
1723 bool is_valid = true;
1724 bool hyphen = false;
1725 for(int i = 0; token[i] != '\0'; i++) {
1726 const char ch = token[i];
1727 if(ch == '-') {
1728 //当前字符是连接符'-'
1729 if(hyphen) {
1730 //已经存在过连接符'-'
1731 is_valid = false;
1732 break;
1733 }
1734 hyphen = true;
1735 if(i == 0 || token[i + 1] == '\0') {
1736 //是否在字符串的开头或结尾
1737 is_valid = false;
1738 break;
1739 }
1740 if(isalpha(token[i - 1]) == 0 || isalpha(token[i + 1]) == 0) {
1741 //前后是否是字母
1742 is_valid = false;
1743 break;
1744 }
1745 } else if(token[i + 1] != '\0' && isalpha(ch) == 0) {
1746 //不是最后一个字符是否不是字母
1747 is_valid = false;
1748 break;
1749 } else if(isdigit(ch) != 0) {
1750 //是否是数字
1751 is_valid = false;
1752 break;
1753 }
1754 }
1755 if(is_valid) {
1756 count++;
1757 }
1758 }
1759 delete[] str;
1760 return count;
1761 }
1762 }// namespace number_of_valid_words_in_a_sentence
1763
1764 namespace the_number_of_weak_characters_in_the_game {
1765 int Solution::numberOfWeakCharacters(vector<vector<int>> &properties) {
1766 //按攻击值从大到小排序。攻击值相同时,按照其防御值从小到大排序
1767 sort(properties.begin(), properties.end(), [](const vector<int> &a, const vector<int> &b) { return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0]; });
1768
1769 int maxDef = 0;
1770 int count = 0;
1771 for(const auto &p: properties) {
1772 if(p[1] < maxDef) {
1773 count++;
1774 } else {
1775 maxDef = p[1];
1776 }
1777 }
1778 return count;
1779 }
1780 }// namespace the_number_of_weak_characters_in_the_game
1781
1782 namespace pattern_matching_lcci {
1783 bool Solution::patternMatching(const string &pattern, const string &value) {
1784 int a_count = 0;
1785 int b_count = 0;
1786 for(const char ch: pattern) {
1787 if(ch == 'a') {
1788 a_count++;
1789 } else {
1790 b_count++;
1791 }
1792 }
1793 if(a_count == 0 || b_count == 0) {
1794 int size = 0;
1795 int count = 0;
1796 if(b_count == 0) {
1797 if(value.length() % a_count != 0) {
1798 return false;
1799 }
1800 size = value.length() / a_count;
1801 count = a_count;
1802 } else {
1803 if(value.length() % b_count != 0) {
1804 return false;
1805 }
1806 size = value.length() / b_count;
1807 count = b_count;
1808 }
1809 const string str = value.substr(0, size);
1810 for(int i = 0; i < count; i++) {
1811 auto s = value.substr(i * size, size);
1812 if(s != str) {
1813 return false;
1814 }
1815 }
1816 return true;
1817 }
1818 for(int a_size = 0; a_size <= value.length() / a_count; a_size++) {
1819 string a;
1820 string b;
1821 if((value.length() - a_size * a_count) % b_count == 0) {
1822 const int b_size = (value.length() - a_size * a_count) / b_count;
1823 string value_local = value;
1824 for(const char ch: pattern) {
1825 if(ch == 'a') {
1826 string a_local = value_local.substr(0, a_size);
1827 if(a.empty()) {
1828 a = a_local;
1829 } else if(a_local != a) {
1830 goto next_loop;
1831 }
1832 value_local = value_local.substr(a_size);
1833 } else {
1834 string b_local = value_local.substr(0, b_size);
1835 if(b.empty()) {
1836 b = b_local;
1837 } else if(b_local != b) {
1838 goto next_loop;
1839 }
1840 value_local = value_local.substr(b_size);
1841 }
1842 }
1843 if(a == b) {
1844 goto next_loop;
1845 }
1846 return true;
1847 }
1848 next_loop:;
1849 }
1850 return false;
1851 }
1852 }// namespace pattern_matching_lcci
1853
1854 namespace map_of_highest_peak {
1855 vector<vector<int>> Solution::highestPeak(vector<vector<int>> &isWater) {
1856 const int m = isWater.size();
1857 const int n = isWater[0].size();
1858 auto *occupied = new bool *[m];
1859 for(int i = 0; i < m; i++) {
1860 occupied[i] = new bool[n];
1861 memset(occupied[i], 0, n * sizeof(bool));
1862 }
1863 auto que = queue<pair<int, int>>();
1864 for(int i = 0; i < m; i++) {
1865 for(int j = 0; j < n; j++) {
1866 if(isWater[i][j] == 1) {
1867 que.push(pair(i, j));
1868 isWater[i][j] = 0;
1869 occupied[i][j] = true;
1870 } else {
1871 isWater[i][j] = 1;
1872 }
1873 }
1874 }
1875 while(!que.empty()) {
1876 pair<int, int> current = que.front();
1877 que.pop();
1878 pair<int, int> nexts[4] = {pair(current.first + 1, current.second),
1879 pair(current.first - 1, current.second),
1880 pair(current.first, current.second + 1),
1881 pair(current.first, current.second - 1)};
1882 for(auto next: nexts) {
1883 if(0 <= next.first && next.first < m && 0 <= next.second && next.second < n && !occupied[next.first][next.second]) {
1884 isWater[next.first][next.second] = isWater[current.first][current.second] + 1;
1885 occupied[next.first][next.second] = true;
1886 que.push(next);
1887 }
1888 }
1889 }
1890 delete[] occupied;
1891 return isWater;
1892 }
1893 }// namespace map_of_highest_peak
1894
1895 namespace uncommon_words_from_two_sentences {
1896 vector<string> Solution::uncommonFromSentences(const string &s1, const string &s2) {
1897 auto ans = vector<string>();
1898 auto um = unordered_map<string, unsigned int>();
1899 auto *const s1_str = new char[s1.length() + 1];
1900 auto *const s2_str = new char[s2.length() + 1];
1901 strcpy(s1_str, s1.c_str());
1902 strcpy(s2_str, s2.c_str());
1903 for(char *word = strtok(s1_str, " "); word != nullptr; word = strtok(nullptr, " ")) {
1904 auto word_str = string(word);
1905 if(!um.contains(word_str)) {
1906 um.insert(pair(word_str, 1));
1907 } else {
1908 um[word_str]++;
1909 }
1910 }
1911 for(char *word = strtok(s2_str, " "); word != nullptr; word = strtok(nullptr, " ")) {
1912 auto word_str = string(word);
1913 if(!um.contains(word_str)) {
1914 um.insert(pair(word_str, 1));
1915 } else {
1916 um[word_str]++;
1917 }
1918 }
1919 for(const auto &p: um) {
1920 if(p.second == 1) {
1921 ans.push_back(p.first);
1922 }
1923 }
1924 delete[] s1_str;
1925 delete[] s2_str;
1926 return ans;
1927 }
1928 }// namespace uncommon_words_from_two_sentences
1929
1930 namespace keep_multiplying_found_values_by_two {
1931 int Solution::findFinalValue(vector<int> &nums, int original) {
1932 restart:;
1933 for(const auto num: nums) {
1934 if(num == original) {
1935 original *= 2;
1936 goto restart;
1937 }
1938 }
1939 return original;
1940 }
1941 }// namespace keep_multiplying_found_values_by_two
1942
1943 namespace all_divisions_with_the_highest_score_of_a_binary_array {
1944 vector<int> Solution::maxScoreIndices(vector<int> &nums) {
1945 const auto n = nums.size();
1946 auto left_0_count = vector<int>();
1947 auto right_1_count = vector<int>();
1948 left_0_count.push_back(0);
1949 right_1_count.push_back(0);
1950 int count = 0;
1951 for(int i = 0; i < n; i++) {
1952 if(nums[i] == 0) {
1953 count++;
1954 }
1955 left_0_count.push_back(count);
1956 }
1957 count = 0;
1958 for(int i = n - 1; i >= 0; i--) {
1959 if(nums[i] == 1) {
1960 count++;
1961 }
1962 right_1_count.push_back(count);
1963 }
1964 right_1_count = vector(right_1_count.rbegin(), right_1_count.rend());
1965 int maximum = 0;
1966 for(int i = 0; i <= n; i++) {
1967 maximum = max(maximum, left_0_count[i] + right_1_count[i]);
1968 }
1969 auto ans = vector<int>();
1970 for(int i = 0; i <= n; i++) {
1971 if(maximum == left_0_count[i] + right_1_count[i]) {
1972 ans.push_back(i);
1973 }
1974 }
1975 return ans;
1976 }
1977 }// namespace all_divisions_with_the_highest_score_of_a_binary_array
1978
1979 namespace find_substring_with_given_hash_value {
1980 string Solution::subStrHash(string s, int power, int modulo, int k, int hashValue) {
1981 power %= modulo;
1982 auto *const pn = new int[k];
1983 pn[0] = 1;
1984 for(int i = 1; i < k; i++) {
1985 pn[i] = static_cast<unsigned long long>(pn[i - 1]) * static_cast<unsigned long long>(power) % modulo;
1986 }
1987
1988 for(int i = 0; i < s.length(); i++) {
1989 unsigned long long hash = 0;
1990 for(int j = 0; j < k; j++) {
1991 hash += static_cast<unsigned long long>((s[i + j] - 'a' + 1) % modulo) * pn[j];
1992 hash %= modulo;
1993 }
1994 if(hash == hashValue) {
1995 return s.substr(i, k);
1996 }
1997 }
1998 delete[] pn;
1999 return "";
2000 }
2001 }// namespace find_substring_with_given_hash_value
2002
2003 namespace groups_of_strings {
2004 vector<int> Solution::groupStrings(vector<string> &words) {
2005 auto ans = vector<int>();
2006 auto nums = vector<unsigned int>();
2007 for(const auto &word: words) {
2008 auto num = compress(word);
2009 nums.push_back(num);
2010 insert(num);
2011 }
2012 for(const auto num: nums) {
2013 for(int i = 0; i < 26; i++) {
2014 auto next = num ^ 1 << i;//添加或删除字符 i
2015 if(parent.contains(next)) {
2016 to_union(num, next);
2017 }
2018 if((num >> i & 1) == 1) {
2019 //存在字符i
2020 for(int j = 0; j < 26; j++) {
2021 if((num >> j & 1) == 0) {
2022 //不存在字符j
2023 auto next = num ^ 1 << i | 1 << j;
2024 if(parent.contains(next)) {
2025 to_union(num, num ^ 1 << i | 1 << j);// 替换字符 i 为 j
2026 }
2027 }
2028 }
2029 }
2030 }
2031 }
2032 ans.push_back(groups);
2033 ans.push_back(max_size);
2034 return ans;
2035 }
2036
2037 unsigned int Solution::compress(const string &word) {
2038 unsigned int ans = 0;
2039 for(const char ch: word) {
2040 ans |= 1 << ch - 'a';
2041 }
2042 return ans;
2043 }
2044
2045 void Solution::insert(unsigned int num) {
2046 parent.insert(pair(num, num));
2047 rank.insert(pair(num, 0));
2048 if(!size.contains(num)) {
2049 size.insert(pair(num, 1));
2050 groups++;
2051 } else {
2052 size[num]++;
2053 max_size = size[num];
2054 }
2055 }
2056
2057 unsigned int Solution::find(unsigned int x) { return x == parent[x] ? x : parent[x] = find(parent[x]); }
2058
2059 void Solution::to_union(unsigned int x1, unsigned int x2) {
2060 const int f1 = find(x1);
2061 const int f2 = find(x2);
2062 if(f1 == f2) {
2063 return;
2064 }
2065 groups--;
2066 if(rank[f1] > rank[f2]) {
2067 parent[f2] = f1;
2068 size[f1] += size[f2];
2069 max_size = max(max_size, size[f1]);
2070 } else {
2071 parent[f1] = f2;
2072 size[f2] += size[f1];
2073 max_size = max(max_size, size[f2]);
2074 if(rank[f1] == rank[f2]) {
2075 ++rank[f2];
2076 }
2077 }
2078 }
2079 }// namespace groups_of_strings
2080
2081 namespace number_of_steps_to_reduce_a_number_to_zero {
2083 if(num == 0) {
2084 return 0;
2085 }
2086 int count = 0;
2087 while(num != 0) {
2088 if((num & 1) == 0) {
2089 count += 1;
2090 } else {
2091 count += 2;
2092 }
2093 num >>= 1;
2094 }
2095 return count - 1;
2096 }
2097 }// namespace number_of_steps_to_reduce_a_number_to_zero
2098
2099 namespace longest_nice_substring {
2100 string Solution::longestNiceSubstring(const string &s) {
2101 auto [max_start, max_len] = dfs(s, 0, s.length() - 1);
2102 if(max_len == 0) {
2103 return "";
2104 }
2105 return s.substr(max_start, max_len);
2106 }
2107
2108 pair<int, int> Solution::dfs(string s, int start, int end) {
2109 if(start == end) {
2110 return {start, 0};
2111 }
2112 int lower = 0;
2113 int upper = 0;
2114 int max_start = 0;
2115 int max_len = 0;
2116 for(int i = start; i <= end; i++) {
2117 const char ch = s[i];
2118 if(islower(ch) != 0) {
2119 lower |= 1 << ch - 'a';
2120 } else {
2121 //isupper
2122 upper |= 1 << ch - 'A';
2123 }
2124 }
2125 if(lower == upper) {
2126 //是美好字符串
2127 return {start, end - start + 1};
2128 }
2129 //不是美好字符串
2130 const int not_nice = lower ^ upper;//无法构成美好字符串的字符
2131 int i = start;
2132 while(i <= end) {
2133 if((not_nice >> tolower(s[i]) - 'a' & 1) == 1) {
2134 //在not_nice中
2135 i++;
2136 continue;
2137 }
2138 int j = i + 1;
2139 while(j <= end && (not_nice >> tolower(s[j]) - 'a' & 1) != 1) {
2140 j++;
2141 }
2142 auto [next_start, next_len] = dfs(s, i, j - 1);
2143 if(max_len < next_len) {
2144 max_len = next_len;
2145 max_start = next_start;
2146 }
2147 i = j;
2148 }
2149 return {max_start, max_len};
2150 }
2151 }// namespace longest_nice_substring
2152
2153 namespace reverse_prefix_of_word {
2154 string Solution::reversePrefix(string word, char ch) {
2155 int i = 0;
2156 for(; i < word.length(); i++) {
2157 if(ch == word[i]) {
2158 break;
2159 }
2160 }
2161 if(i == word.length()) {
2162 return word;
2163 }
2164 string prefix = word.substr(0, i + 1);
2165 const string suffix = word.substr(i + 1);
2166 const auto xiferp = string(prefix.rbegin(), prefix.rend());
2167 return xiferp + suffix;
2168 }
2169 }// namespace reverse_prefix_of_word
2170
2171 namespace find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k {
2173 auto fibb = set<int, greater<>>();
2174 fibb.insert(1);
2175 int prev_1 = 1;
2176 int next = 2;
2177 while(next <= k) {
2178 fibb.insert(next);
2179 const int prev_2 = prev_1;
2180 prev_1 = next;
2181 next = prev_1 + prev_2;
2182 }
2183 return find_min(fibb, k, fibb.begin());
2184 }
2185
2186 int Solution::find_min(set<int, greater<>> &fibb, int k, set<int, greater<>>::iterator begin) {
2187 const auto i = lower_bound(begin, fibb.end(), k, greater<int>());
2188 if(k == *i) {
2189 return 1;
2190 }
2191 return 1 + find_min(fibb, k - *i, i);
2192 }
2193 }// namespace find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k
2194
2195 namespace number_of_rectangles_that_can_form_the_largest_square {
2196 int Solution::countGoodRectangles(vector<vector<int>> &rectangles) {
2197 auto m = map<int, int>();
2198 for(auto rectangle: rectangles) {
2199 int k = min(rectangle[0], rectangle[1]);
2200 m[k]++;
2201 }
2202 return (*m.rbegin()).second;
2203 }
2204 }// namespace number_of_rectangles_that_can_form_the_largest_square
2205
2206 namespace path_with_maximum_gold {
2207 int Solution::getMaximumGold(vector<vector<int>> &grid) {
2208 const int m = grid.size();
2209 const int n = grid[0].size();
2210 int ans = 0;
2211 for(int i = 0; i < m; i++) {
2212 for(int j = 0; j < n; j++) {
2213 if(grid[i][j] != 0) {
2214 auto *occupied = new bool *[m];
2215 for(int k = 0; k < m; k++) {
2216 occupied[k] = new bool[n];
2217 memset(occupied[k], 0, n * sizeof(bool));
2218 }
2219 occupied[i][j] = true;
2220 ans = max(ans, get_sum(grid[i][j], i, j, m, n, grid, occupied));
2221 for(int k = 0; k < m; k++) {
2222 delete[] occupied[k];
2223 }
2224 delete[] occupied;
2225 }
2226 }
2227 }
2228 return ans;
2229 }
2230
2231 int Solution::get_sum(int current, int x, int y, int m, int n, vector<vector<int>> &grid, bool **occupied) {
2232 pair<int, int> nexts[] = {make_pair(x + 1, y), make_pair(x - 1, y), make_pair(x, y + 1), make_pair(x, y - 1)};
2233 int maximum = current;
2234 for(auto [next_x, next_y]: nexts) {
2235 if(0 <= next_x && next_x < m && 0 <= next_y && next_y < n && grid[next_x][next_y] != 0 && !occupied[next_x][next_y]) {
2236 auto *occupied_cpy = new bool *[m];
2237 for(int i = 0; i < m; i++) {
2238 occupied_cpy[i] = new bool[n];
2239 memcpy(occupied_cpy[i], occupied[i], n * sizeof(bool));
2240 }
2241 occupied_cpy[next_x][next_y] = true;
2242 maximum = max(maximum, get_sum(current + grid[next_x][next_y], next_x, next_y, m, n, grid, occupied_cpy));
2243 for(int i = 0; i < m; i++) {
2244 delete[] occupied_cpy[i];
2245 }
2246 delete[] occupied_cpy;
2247 }
2248 }
2249 return maximum;
2250 }
2251 }// namespace path_with_maximum_gold
2252
2253 namespace minimum_sum_of_four_digit_number_after_splitting_digits {
2255 auto oss = ostringstream();
2256 oss << num;
2257 const string str = oss.str();
2258 int nums[4];
2259 for(int i = 0; i < 4; i++) {
2260 nums[i] = str[i] - '0';
2261 }
2262 sort(nums, nums + 4);
2263 return nums[0] * 10 + nums[1] * 10 + nums[2] + nums[3];
2264 }
2265 }// namespace minimum_sum_of_four_digit_number_after_splitting_digits
2266
2267 namespace partition_array_according_to_given_pivot {
2268 vector<int> Solution::pivotArray(vector<int> &nums, int pivot) {
2269 auto less = vector<int>();
2270 auto equal = vector<int>();
2271 auto greater = vector<int>();
2272 for(auto num: nums) {
2273 if(num < pivot) {
2274 less.push_back(num);
2275 } else if(num == pivot) {
2276 equal.push_back(num);
2277 } else {
2278 greater.push_back(num);
2279 }
2280 }
2281 less.insert(less.end(), equal.begin(), equal.end());
2282 less.insert(less.end(), greater.begin(), greater.end());
2283 return less;
2284 }
2285 }// namespace partition_array_according_to_given_pivot
2286
2287 namespace minimum_cost_to_set_cooking_time {
2288 int Solution::minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {
2289 int ans = (moveCost + pushCost) * 4;
2290 int minute = targetSeconds / 60;
2291 int second = targetSeconds % 60;
2292 while(minute > 99) {
2293 minute -= 1;
2294 second += 60;
2295 }
2296 const int num[4] = {minute / 10, minute % 10, second / 10, second % 10};
2297 ans = min(ans, get_cost(startAt, moveCost, pushCost, num));
2298 if(second + 60 < 100 && minute - 1 >= 0) {
2299 second += 60;
2300 minute -= 1;
2301 const int num[4] = {minute / 10, minute % 10, second / 10, second % 10};
2302 ans = min(ans, get_cost(startAt, moveCost, pushCost, num));
2303 }
2304 return ans;
2305 }
2306
2307 int Solution::get_cost(int startAt, int moveCost, int pushCost, const int num[4]) {
2308 int cost = 0;
2309 int current = startAt;
2310 bool flag = true;
2311 for(int i = 0; i < 4; i++) {
2312 if(num[i] == 0 && flag) {
2313 continue;
2314 }
2315 flag = false;
2316 if(num[i] != current) {
2317 cost += moveCost;
2318 current = num[i];
2319 }
2320 cost += pushCost;
2321 }
2322 return cost;
2323 }
2324 }// namespace minimum_cost_to_set_cooking_time
2325
2326 namespace minimum_difference_in_sums_after_removal_of_elements {
2327 long long Solution::minimumDifference(vector<int> &nums) {
2328 const int n = nums.size() / 3;
2329 auto *left_sum = new long long[n];
2330 auto *right_sum = new long long[n];
2331 long long left_min = 0;
2332 long long right_max = 0;
2333 auto left_n = priority_queue<int>();
2334 auto right_n = priority_queue<int, vector<int>, greater<>>();
2335 for(int i = 0; i < n; i++) {
2336 left_n.push(nums[i]);
2337 left_min += nums[i];
2338 }
2339 for(int i = 3 * n - 1; i >= 2 * n; i--) {
2340 right_n.push(nums[i]);
2341 right_max += nums[i];
2342 }
2343 const long long left_min_preserve = left_min;
2344 const long long right_max_preserve = right_max;
2345 left_sum[0] = left_min;
2346 right_sum[n - 1] = right_max;
2347 for(int i = n; i < 2 * n; i++) {
2348 if(nums[i] < left_n.top()) {
2349 left_min += nums[i] - left_n.top();
2350 left_n.pop();
2351 left_n.push(nums[i]);
2352 }
2353 left_sum[i - n] = left_min;
2354 }
2355 for(int i = 2 * n - 1; i >= n; i--) {
2356 if(nums[i] > right_n.top()) {
2357 right_max += nums[i] - right_n.top();
2358 right_n.pop();
2359 right_n.push(nums[i]);
2360 }
2361 right_sum[i - n] = right_max;
2362 }
2363 long long ans = left_min_preserve - right_sum[0];
2364 for(int i = 0; i < n - 1; i++) {
2365 ans = min(ans, left_sum[i] - right_sum[i + 1]);
2366 }
2367 ans = min(ans, left_sum[n - 1] - right_max_preserve);
2368 delete[] left_sum;
2369 delete[] right_sum;
2370 return ans;
2371 }
2372 }// namespace minimum_difference_in_sums_after_removal_of_elements
2373
2374 namespace sum_of_unique_elements {
2375 int Solution::sumOfUnique(vector<int> &nums) {
2376 auto um = unordered_map<int, int>();
2377 for(auto num: nums) {
2378 um[num]++;
2379 }
2380 int ans = 0;
2381 for(auto [k, v]: um) {
2382 if(v == 1) {
2383 ans += k;
2384 }
2385 }
2386 return ans;
2387 }
2388 }// namespace sum_of_unique_elements
2389
2390 namespace sort_even_and_odd_indices_independently {
2391 vector<int> Solution::sortEvenOdd(vector<int> &nums) {
2392 vector<int> even;
2393 vector<int> odd;
2394 vector<int> ans;
2395 for(int i = 0; i < nums.size(); i++) {
2396 if(i % 2 == 0) {
2397 even.push_back(nums[i]);
2398 } else {
2399 odd.push_back(nums[i]);
2400 }
2401 }
2402 sort(even.begin(), even.end());
2403 sort(odd.begin(), odd.end(), greater<int>());
2404 for(int i = 0; i < odd.size(); i++) {
2405 ans.push_back(even[i]);
2406 ans.push_back(odd[i]);
2407 }
2408 if(even.size() > odd.size()) {
2409 ans.push_back(even.back());
2410 }
2411 return ans;
2412 }
2413 }// namespace sort_even_and_odd_indices_independently
2414
2415 namespace smallest_value_of_the_rearranged_number {
2416 long long Solution::smallestNumber(long long num) {
2417 bool positive = num > 0;
2418 auto oss = ostringstream();
2419 num = abs(num);
2420 oss << num;
2421 vector<int> n;
2422 for(char ch: oss.str()) {
2423 n.push_back(ch - '0');
2424 }
2425 sort(n.begin(), n.end());
2426 vector<int> ans;
2427 if(positive) {
2428 for(auto i: n) {
2429 if(i != 0) {
2430 ans.push_back(i);
2431 }
2432 }
2433 for(auto i: n) {
2434 if(i == 0) {
2435 ans.insert(ans.begin() + 1, i);
2436 }
2437 }
2438 } else {
2439 for(int i = n.size() - 1; i >= 0; i--) {
2440 ans.push_back(n[i]);
2441 }
2442 }
2443 oss = ostringstream();
2444 if(!positive) {
2445 oss << '-';
2446 }
2447 for(auto i: ans) {
2448 oss << i;
2449 }
2450 auto iss = istringstream(oss.str());
2451 long long a;
2452 iss >> a;
2453 return a;
2454 }
2455 }// namespace smallest_value_of_the_rearranged_number
2456
2457 namespace design_bitset {
2458 Bitset::Bitset(int size) {
2459 this->size = size;
2460 one1 = new set<unsigned int>();
2461 zero0 = new set<unsigned int>();
2462 for(int i = 0; i < size; i++) {
2463 zero0->insert(i);
2464 }
2465 }
2466
2467 void Bitset::fix(int idx) const {
2468 zero0->erase(idx);
2469 one1->insert(idx);
2470 }
2471
2472 void Bitset::unfix(int idx) const {
2473 zero0->insert(idx);
2474 one1->erase(idx);
2475 }
2476
2478 auto *const tmp = one1;
2479 one1 = zero0;
2480 zero0 = tmp;
2481 }
2482
2483 bool Bitset::all() const { return zero0->empty(); }
2484
2485 bool Bitset::one() const { return !one1->empty(); }
2486
2487 int Bitset::count() const { return one1->size(); }
2488
2489 string Bitset::toString() const {
2490 auto oss = ostringstream();
2491 auto c1 = one1->begin();
2492 auto c0 = zero0->begin();
2493 for(int i = 0; i < size; i++) {
2494 if(c1 != one1->end() && *c1 == i) {
2495 oss << 1;
2496 ++c1;
2497 } else if(c0 != zero0->end() && *c0 == i) {
2498 oss << 0;
2499 ++c0;
2500 }
2501 }
2502 return oss.str();
2503 }
2504 }// namespace design_bitset
2505
2506 namespace longest_happy_string {
2507 string Solution::longestDiverseString(int a, int b, int c) {
2508 auto oss = ostringstream();
2509 int count = 0;
2510 char prev = '0';
2511 char ch[3] = {};
2512 sort(ch, a, b, c);
2513 while(a != 0 || b != 0 || c != 0) {
2514 if(!(count == 2 && prev == ch[2] && *get_p(ch[2], &a, &b, &c) > 0)) {
2515 oss << ch[2];
2516 (*get_p(ch[2], &a, &b, &c))--;
2517 if(prev == ch[2]) {
2518 count++;
2519 } else {
2520 prev = ch[2];
2521 count = 1;
2522 }
2523 } else if(!(count == 2 && prev == ch[1]) && *get_p(ch[1], &a, &b, &c) > 0) {
2524 oss << ch[1];
2525 (*get_p(ch[1], &a, &b, &c))--;
2526 if(prev == ch[1]) {
2527 count++;
2528 } else {
2529 prev = ch[1];
2530 count = 1;
2531 }
2532 } else if(!(count == 2 && prev == ch[0]) && *get_p(ch[0], &a, &b, &c) > 0) {
2533 oss << ch[0];
2534 (*get_p(ch[0], &a, &b, &c))--;
2535 if(prev == ch[0]) {
2536 count++;
2537 } else {
2538 prev = ch[0];
2539 count = 1;
2540 }
2541 } else {
2542 return oss.str();
2543 }
2544 sort(ch, a, b, c);
2545 }
2546 return oss.str();
2547 }
2548
2549 void Solution::sort(char *ch, int a, int b, int c) {
2550 int minimum = a;
2551 ch[0] = 'a';
2552 int maximum = b;
2553 ch[2] = 'b';
2554 if(minimum > b) {
2555 minimum = b;
2556 ch[0] = 'b';
2557 }
2558 if(minimum > c) {
2559 minimum = c;
2560 ch[0] = 'c';
2561 }
2562 if(maximum < a) {
2563 maximum = a;
2564 ch[2] = 'a';
2565 }
2566 if(maximum < c) {
2567 maximum = c;
2568 ch[2] = 'c';
2569 }
2570 ch[1] = 'a' + 'b' + 'c' - ch[0] - ch[2];
2571 }
2572
2573 int *Solution::get_p(char ch, int *a, int *b, int *c) {
2574 switch(ch) {
2575 case 'a': return a;
2576 case 'b': return b;
2577 case 'c': return c;
2578 default: return nullptr;
2579 }
2580 }
2581 }// namespace longest_happy_string
2582
2583 namespace grid_illumination {
2584 vector<int> Solution::gridIllumination(int n, vector<vector<int>> &lamps, vector<vector<int>> &queries) {
2585 auto ls = unordered_set<pair<int, int>, pair_hash>();
2586 auto row = unordered_map<int, int>();
2587 auto col = unordered_map<int, int>();
2588 auto diag_down = unordered_map<int, int>();
2589 auto diag_up = unordered_map<int, int>();
2590 for(auto lamp: lamps) {
2591 int x = lamp[0];
2592 int y = lamp[1];
2593 auto p = make_pair(x, y);
2594 if(!ls.contains(p)) {
2595 ls.insert(p);
2596 row[x]++;
2597 col[y]++;
2598 diag_down[n - x + y]++;
2599 diag_up[x + y]++;
2600 }
2601 }
2602 auto ans = vector<int>();
2603 for(auto query: queries) {
2604 int query_x = query[0];
2605 int query_y = query[1];
2606 if(row[query_x] > 0 || col[query_y] > 0 || diag_down[n - query_x + query_y] > 0 || diag_up[query_x + query_y] > 0) {
2607 ans.push_back(1);
2608 } else {
2609 ans.push_back(0);
2610 }
2611 pair<int, int> adjacents[9] = {make_pair(query_x + 1, query_y + 1), make_pair(query_x + 1, query_y), make_pair(query_x + 1, query_y - 1),
2612 make_pair(query_x, query_y + 1), make_pair(query_x, query_y), make_pair(query_x, query_y - 1),
2613 make_pair(query_x - 1, query_y + 1), make_pair(query_x - 1, query_y), make_pair(query_x - 1, query_y - 1)};
2614 for(auto adjacent: adjacents) {
2615 if(ls.contains(adjacent)) {
2616 ls.erase(adjacent);
2617 auto [x, y] = adjacent;
2618 row[x]--;
2619 col[y]--;
2620 diag_down[n - x + y]--;
2621 diag_up[x + y]--;
2622 }
2623 }
2624 }
2625 return ans;
2626 }
2627
2628 unsigned long long pair_hash::operator()(const pair<int, int> &p) const { return static_cast<unsigned long long>(p.first) * 1000000000 + p.second; }
2629 }// namespace grid_illumination
2630
2631 namespace count_number_of_pairs_with_absolute_difference_k {
2632 int Solution::countKDifference(vector<int> &nums, int k) {
2633 int ans = 0;
2634 for(int i = 0; i < nums.size(); i++) {
2635 for(int j = i + 1; j < nums.size(); j++) {
2636 if(abs(nums[i] - nums[j]) == k) {
2637 ans++;
2638 }
2639 }
2640 }
2641 return ans;
2642 }
2643 }// namespace count_number_of_pairs_with_absolute_difference_k
2644
2645 namespace simplified_fractions {
2646 vector<string> Solution::simplifiedFractions(int n) {
2647 auto ans = vector<string>();
2648 for(int denominator = 2; denominator <= n; denominator++) {
2649 for(int numerator = 1; numerator < denominator; numerator++) {
2650 if(gcd(denominator, numerator) != 1) {
2651 continue;
2652 }
2653 auto oss = ostringstream();
2654 oss << numerator << "/" << denominator;
2655 ans.push_back(oss.str());
2656 }
2657 }
2658 return ans;
2659 }
2660
2661 int Solution::gcd(int m, int n) { return n != 0 ? gcd(n, m % n) : m; }
2662 }// namespace simplified_fractions
2663
2664 namespace minimum_difference_between_highest_and_lowest_of_k_scores {
2665 int Solution::minimumDifference(vector<int> &nums, int k) {
2666 int ans = 100000;
2667 sort(nums.begin(), nums.end());
2668 for(int i = 0; i + k - 1 < nums.size(); i++) {
2669 ans = min(ans, nums[i + k - 1] - nums[i]);
2670 }
2671 return ans;
2672 }
2673 }// namespace minimum_difference_between_highest_and_lowest_of_k_scores
2674
2675 namespace number_of_enclaves {
2676 int Solution::numEnclaves(vector<vector<int>> &grid) {
2677 int sum = 0;
2678 const int m = grid.size();
2679 const int n = grid[0].size();
2680 auto que = queue<pair<int, int>>();
2681 for(int i = 0; i < m; i++) {
2682 for(int j = 0; j < n; j++) {
2683 if(grid[i][j] == 1) {
2684 sum++;
2685 if(i == 0 || i == m - 1 || j == 0 || j == n - 1) {
2686 que.push(make_pair(i, j));
2687 grid[i][j] = 0;
2688 }
2689 }
2690 }
2691 }
2692 while(!que.empty()) {
2693 auto [x, y] = que.front();
2694 sum--;
2695 que.pop();
2696 pair<int, int> nexts[4] = {make_pair(x + 1, y), make_pair(x - 1, y), make_pair(x, y + 1), make_pair(x, y - 1)};
2697 for(auto next: nexts) {
2698 auto [next_x, next_y] = next;
2699 if(0 <= next_x && next_x < m && 0 <= next_y && next_y < n && grid[next_x][next_y] != 0) {
2700 que.push(next);
2701 grid[next_x][next_y] = 0;
2702 }
2703 }
2704 }
2705 return sum;
2706 }
2707 }// namespace number_of_enclaves
2708
2709 namespace maximum_number_of_balloons {
2710 int Solution::maxNumberOfBalloons(const string &text) {
2711 int b = 0;
2712 int a = 0;
2713 int l = 0;
2714 int o = 0;
2715 int n = 0;
2716 for(const char ch: text) {
2717 switch(ch) {
2718 case 'b':
2719 b++;
2720 break;
2721 case 'a':
2722 a++;
2723 break;
2724 case 'l':
2725 l++;
2726 break;
2727 case 'o':
2728 o++;
2729 break;
2730 case 'n':
2731 n++;
2732 break;
2733 }
2734 }
2735 l /= 2;
2736 o /= 2;
2737 int ans = b;
2738 ans = min(ans, a);
2739 ans = min(ans, l);
2740 ans = min(ans, o);
2741 ans = min(ans, n);
2742 return ans;
2743 }
2744 }// namespace maximum_number_of_balloons
2745
2746 namespace swap_adjacent_in_lr_string {
2747 bool Solution::canTransform(const string &start, const string &end) {
2748 auto oss_start = ostringstream();
2749 auto oss_end = ostringstream();
2750 auto i_start = vector<int>();
2751 auto i_end = vector<int>();
2752 for(int i = 0; i < start.size(); i++) {
2753 char ch = start[i];
2754 if(ch == 'R' || ch == 'L') {
2755 oss_start << ch;
2756 i_start.push_back(i);
2757 }
2758 }
2759 for(int i = 0; i < end.size(); i++) {
2760 char ch = end[i];
2761 if(ch == 'R' || ch == 'L') {
2762 oss_end << ch;
2763 i_end.push_back(i);
2764 }
2765 }
2766 string str_start = oss_start.str();
2767 string str_end = oss_end.str();
2768 if(str_start != str_end) {
2769 return false;
2770 }
2771 for(int i = 0; i < i_start.size(); i++) {
2772 if(str_start[i] == 'R') {
2773 if(i_start[i] > i_end[i]) {
2774 return false;
2775 }
2776 } else {
2777 //L
2778 if(i_start[i] < i_end[i]) {
2779 return false;
2780 }
2781 }
2782 }
2783 return true;
2784 }
2785 }// namespace swap_adjacent_in_lr_string
2786
2787 namespace count_operations_to_obtain_zero {
2788 int Solution::countOperations(int num1, int num2) {
2789 int count = 0;
2790 while(num1 != 0 && num2 != 0) {
2791 if(num1 > num2) {
2792 count += num1 / num2;
2793 num1 = num1 % num2;
2794 } else {
2795 count += num2 / num1;
2796 num2 = num2 % num1;
2797 }
2798 }
2799 return count;
2800 }
2801 }// namespace count_operations_to_obtain_zero
2802
2803 namespace minimum_operations_to_make_the_array_alternating {
2804 int Solution::minimumOperations(vector<int> &nums) {
2805 int a_sum = 0;
2806 int b_sum = 0;
2807 auto a = unordered_map<int, int>();
2808 auto b = unordered_map<int, int>();
2809 for(int i = 0; i < nums.size(); i++) {
2810 if(i % 2 == 0) {
2811 a[nums[i]]++;
2812 a_sum++;
2813 } else {
2814 b[nums[i]]++;
2815 b_sum++;
2816 }
2817 }
2818 int max_num = 0;
2819 int maximum = 0;
2820 int ans1 = 0;
2821 for(const auto i: a) {
2822 if(maximum < i.second) {
2823 maximum = i.second;
2824 max_num = i.first;
2825 }
2826 }
2827 ans1 += a_sum - maximum;
2828 maximum = 0;
2829 for(const auto i: b) {
2830 if(i.first != max_num && maximum < i.second) {
2831 maximum = i.second;
2832 }
2833 }
2834 ans1 += b_sum - maximum;
2835
2836 int ans2 = 0;
2837 max_num = 0;
2838 maximum = 0;
2839 for(const auto i: b) {
2840 if(maximum < i.second) {
2841 maximum = i.second;
2842 max_num = i.first;
2843 }
2844 }
2845 ans2 += b_sum - maximum;
2846 maximum = 0;
2847 for(const auto i: a) {
2848 if(i.first != max_num && maximum < i.second) {
2849 maximum = i.second;
2850 }
2851 }
2852 ans2 += a_sum - maximum;
2853 return min(ans1, ans2);
2854 }
2855 }// namespace minimum_operations_to_make_the_array_alternating
2856
2857 namespace removing_minimum_number_of_magic_beans {
2858 long long Solution::minimumRemoval(vector<int> &beans) {
2859 sort(beans.begin(), beans.end());
2860 long long sum = 0;
2861 long long maximum = 0;
2862 for(int i = 0; i < beans.size(); i++) {
2863 sum += beans[i];
2864 maximum = max(maximum, static_cast<long long>(beans[i] * (beans.size() - i)));
2865 }
2866 return sum - maximum;
2867 }
2868 }// namespace removing_minimum_number_of_magic_beans
2869
2870 namespace maximum_and_sum_of_array {
2871 int Solution::maximumANDSum(vector<int> &nums, int numSlots) {
2872 int ans = 0;
2873 vector<int> max_and_sum_of_status(1 << numSlots * 2);
2874 for(unsigned int status = 0; status < max_and_sum_of_status.size(); ++status) {
2875 //status:已经放置数字的篮子的集合
2876 const int one_count = popcount(status);
2877 if(one_count >= nums.size()) {
2878 continue;
2879 }
2880 for(int next_slot = 0; next_slot < numSlots * 2; ++next_slot) {
2881 if((status & 1 << next_slot) == 0) {
2882 // next_slot是空的
2883 const int next_status = status | 1 << next_slot;
2884 const auto slot_num = next_slot / 2 + 1;
2885 max_and_sum_of_status[next_status] = max(max_and_sum_of_status[next_status], max_and_sum_of_status[status] + (slot_num & nums[one_count]));//放置第onecount个数字
2886 ans = max(ans, max_and_sum_of_status[next_status]);
2887 }
2888 }
2889 }
2890 return ans;
2891 }
2892 }// namespace maximum_and_sum_of_array
2893
2894 namespace single_element_in_a_sorted_array {
2895 int Solution::singleNonDuplicate(vector<int> &nums) {
2896 int l = 0;
2897 int r = nums.size() - 1;
2898 while(l < r) {
2899 if(l + 1 == r) {
2900 if(l == 0) {
2901 return nums[l];
2902 }
2903 if(r == nums.size() - 1) {
2904 return nums[r];
2905 }
2906 if(nums[l - 1] == nums[l]) {
2907 return nums[r];
2908 }
2909 return nums[l];
2910 }
2911 const int m = (l + r) / 2;
2912 int tmp = m;
2913 if(nums[m + 1] == nums[m]) {
2914 tmp = m + 1;
2915 }
2916 if(tmp % 2 == 0) {
2917 //在左边
2918 r = m;
2919 } else {
2920 //在右边
2921 l = m;
2922 }
2923 }
2924 return nums[l];
2925 }
2926 }// namespace single_element_in_a_sorted_array
2927
2928 namespace lucky_numbers_in_a_matrix {
2929 vector<int> Solution::luckyNumbers(vector<vector<int>> &matrix) {
2930 auto ans = vector<int>();
2931 const auto m = matrix.size();
2932 const auto n = matrix[0].size();
2933 auto *minimum = new int[m];
2934 memset(minimum, 50, m * sizeof(int));
2935 auto *maximum = new int[n];
2936 memset(maximum, 0, n * sizeof(int));
2937 for(int i = 0; i < m; i++) {
2938 for(int j = 0; j < n; j++) {
2939 minimum[i] = min(minimum[i], matrix[i][j]);
2940 maximum[j] = max(maximum[j], matrix[i][j]);
2941 }
2942 }
2943 for(int i = 0; i < m; i++) {
2944 for(int j = 0; j < n; j++) {
2945 if(matrix[i][j] == minimum[i] && matrix[i][j] == maximum[j]) {
2946 ans.push_back(matrix[i][j]);
2947 }
2948 }
2949 }
2950 delete[] minimum;
2951 delete[] maximum;
2952 return ans;
2953 }
2954 }// namespace lucky_numbers_in_a_matrix
2955
2956 namespace number_of_ways_to_reconstruct_a_tree {
2957 int Solution::checkWays(vector<vector<int>> &pairs) {
2958 unordered_map<int, unordered_set<int>> adj;
2959 for(auto &p: pairs) {
2960 adj[p[0]].emplace(p[1]);
2961 adj[p[1]].emplace(p[0]);
2962 }
2963 /* 检测是否存在根节点*/
2964 int root = -1;
2965 for(auto &[node, neighbours]: adj) {
2966 if(neighbours.size() == adj.size() - 1) {
2967 root = node;
2968 break;
2969 }
2970 }
2971 if(root == -1) {
2972 return 0;
2973 }
2974
2975 int res = 1;
2976 for(auto &[node, neighbours]: adj) {
2977 if(node == root) {
2978 continue;
2979 }
2980 const int currDegree = neighbours.size();
2981 int parent = -1;
2982 int parentDegree = INT_MAX;
2983
2984 /* 根据 degree 的大小找到 node 的父节点 parent */
2985 for(const auto &neighbour: neighbours) {
2986 if(adj[neighbour].size() < parentDegree && adj[neighbour].size() >= currDegree) {
2987 parent = neighbour;
2988 parentDegree = adj[neighbour].size();
2989 }
2990 }
2991 if(parent == -1) {
2992 return 0;
2993 }
2994
2995 /* 检测 neighbours 是否是 adj[parent] 的子集 */
2996 for(const auto &neighbour: neighbours) {
2997 if(neighbour == parent) {
2998 continue;
2999 }
3000 if(static_cast<unsigned int>(adj[parent].contains(neighbour)) == 0U) {
3001 return 0;
3002 }
3003 }
3004 if(parentDegree == currDegree) {
3005 res = 2;
3006 }
3007 }
3008 return res;
3009 }
3010 }// namespace number_of_ways_to_reconstruct_a_tree
3011
3012 namespace find_center_of_star_graph {
3013 int Solution::findCenter(vector<vector<int>> &edges) {
3014 auto um = unordered_map<int, int>();
3015 for(auto edge: edges) {
3016 um[edge[0]]++;
3017 um[edge[1]]++;
3018 if(um[edge[0]] > 1) {
3019 return edge[0];
3020 }
3021 if(um[edge[1]] > 1) {
3022 return edge[1];
3023 }
3024 }
3025 return 0;
3026 }
3027 }// namespace find_center_of_star_graph
3028
3029 namespace knight_probability_in_chessboard {
3030 double Solution::knightProbability(int n, int k, int row, int column) {
3031 if(k == 0) {
3032 return 1;
3033 }
3034 const auto s = status(k, row, column);
3035 if(um.count(s) == 1) {
3036 return um[s];
3037 }
3038 int off = 0;
3039 pair<int, int> nexts[8] = {make_pair(row - 2, column - 1),
3040 make_pair(row - 2, column + 1),
3041 make_pair(row + 2, column - 1),
3042 make_pair(row + 2, column + 1),
3043 make_pair(row - 1, column - 2),
3044 make_pair(row - 1, column + 2),
3045 make_pair(row + 1, column - 2),
3046 make_pair(row + 1, column + 2)};
3047 double sum = 0;
3048 for(auto [next_x, next_y]: nexts) {
3049 if(0 <= next_x && next_x < n && 0 <= next_y && next_y < n) {
3050 sum += knightProbability(n, k - 1, next_x, next_y);
3051 }
3052 }
3053 const double ans = sum / 8;
3054 um[s] = ans;
3055 return ans;
3056 }
3057
3058 unsigned int status_hash::operator()(const status &s) const { return s.k * 25 * 25 + s.row * 25 + s.column; }
3059
3060 bool status_equal::operator()(const status &s1, const status &s2) const { return s1.k == s2.k && s1.row == s2.row && s1.column == s2.column; }
3061 }// namespace knight_probability_in_chessboard
3062
3063 namespace pancake_sorting {
3064 vector<int> Solution::pancakeSort(vector<int> &arr) {
3065 auto ans = vector<int>();
3066 const int n = arr.size();
3067 auto *current = new int[n];
3068 auto *sorted = new int[n];
3069 for(int i = 0; i < n; i++) {
3070 current[i] = arr[i];
3071 sorted[i] = arr[i];
3072 }
3073 sort(sorted, sorted + n);
3074 RESTART:
3075 for(int i = n - 1; i >= 0; i--) {
3076 if(current[i] != sorted[i]) {
3077 const int target = sorted[i];
3078 int target_i = -1;
3079 for(int j = 0; j <= i; j++) {
3080 if(current[j] == target) {
3081 target_i = j + 1;
3082 break;
3083 }
3084 }
3085 if(target_i == 1) {
3086 target_i = i + 1;
3087 }
3088 ans.push_back(target_i);
3089 for(int j = 0; j < target_i / 2; j++) {
3090 swap(current[j], current[target_i - j - 1]);
3091 }
3092 goto RESTART;
3093 }
3094 }
3095 delete[] current;
3096 delete[] sorted;
3097 return ans;
3098 }
3099 }// namespace pancake_sorting
3100
3101 namespace count_equal_and_divisible_pairs_in_an_array {
3102 int Solution::countPairs(vector<int> &nums, int k) {
3103 int ans = 0;
3104 for(int i = 0; i + 1 < nums.size(); i++) {
3105 for(int j = i + 1; j < nums.size(); j++) {
3106 if(nums[i] == nums[j] && i * j % k == 0) {
3107 ans++;
3108 }
3109 }
3110 }
3111 return ans;
3112 }
3113 }// namespace count_equal_and_divisible_pairs_in_an_array
3114
3115 namespace find_three_consecutive_integers_that_sum_to_a_given_number {
3116 vector<long long> Solution::sumOfThree(long long int num) {
3117 if(num % 3 == 0) {
3118 const long long mid = num / 3;
3119 vector ans = {mid - 1, mid, mid + 1};
3120 return ans;
3121 }
3122 return {};
3123 }
3124 }// namespace find_three_consecutive_integers_that_sum_to_a_given_number
3125
3126 namespace maximum_split_of_positive_even_integers {
3127 vector<long long> Solution::maximumEvenSplit(long long int finalSum) {
3128 if(finalSum % 2 != 0) {
3129 return {};
3130 }
3131 if(finalSum == 4) {
3132 return {4};
3133 }
3134 auto ans = vector<long long int>();
3135 ans.push_back(2);
3136 finalSum -= 2;
3137 for(long long i = 4; i <= finalSum; i += 2) {
3138 const long long int next = finalSum - i;
3139 if(next > i) {
3140 ans.push_back(i);
3141 finalSum = next;
3142 } else {
3143 ans.push_back(finalSum);
3144 break;
3145 }
3146 }
3147 return ans;
3148 }
3149 }// namespace maximum_split_of_positive_even_integers
3150
3151 namespace count_good_triplets_in_an_array {
3152 long long Solution::goodTriplets(vector<int> &nums1, vector<int> &nums2) {
3153 const int n = nums1.size();
3154 FenwickTree<int> occur(n);
3155 unordered_map<int, int> pos;
3156 for(int i = 0; i < n; ++i) {
3157 pos[nums2[i]] = i + 1;
3158 }
3159 long long ans = 0;
3160 for(int i = 0; i < n; ++i) {
3161 const int idx = pos[nums1[i]];
3162 const int left = occur.query(idx);
3163 const int right = n - idx - (occur.query(n) - occur.query(idx));
3164 ans += 1LL * left * right;
3165 occur.update(idx, 1);
3166 }
3167
3168 return ans;
3169 }
3170 }// namespace count_good_triplets_in_an_array
3171
3172 namespace count_integers_with_even_digit_sum {
3173 int Solution::countEven(int num) {
3174 int ans = 0;
3175 for(int i = 1; i <= num; i++) {
3176 stringstream ss;
3177 ss << i;
3178 char ch;
3179 int sum = 0;
3180 while(ss >> ch) {
3181 sum += ch - '0';
3182 }
3183 if(sum % 2 == 0) {
3184 ans++;
3185 }
3186 }
3187 return ans;
3188 }
3189 }// namespace count_integers_with_even_digit_sum
3190
3191 namespace merge_nodes_in_between_zeros {
3193 while(head != nullptr && head->val == 0) {
3194 head = head->next;
3195 }
3196 auto *prev = head;
3197 while(head != nullptr && head->next != nullptr) {
3198 if(head->next->val != 0) {
3199 head->val += head->next->val;
3200 head->next = head->next->next;
3201 } else {
3202 head->next = head->next->next;
3203 head = head->next;
3204 }
3205 }
3206 return prev;
3207 }
3208 }// namespace merge_nodes_in_between_zeros
3209
3210 namespace construct_string_with_repeat_limit {
3211 string Solution::repeatLimitedString(const string &s, int repeatLimit) {
3212 int ch[26] = {};
3213 for(const char c: s) {
3214 ch[c - 'a']++;
3215 }
3216 auto oss = ostringstream();
3217 for(int i = 25; i >= 0; i--) {
3218 int repeat = 0;
3219 while(ch[i] != 0) {
3220 oss << static_cast<char>(i + 'a');
3221 repeat++;
3222 ch[i]--;
3223 if(repeat == repeatLimit && ch[i] != 0) {
3224 for(int j = i - 1; j >= 0; j--) {
3225 if(ch[j] > 0) {
3226 oss << static_cast<char>(j + 'a');
3227 ch[j]--;
3228 repeat = 0;
3229 break;
3230 }
3231 }
3232 if(repeat != 0) {
3233 return oss.str();
3234 }
3235 }
3236 }
3237 }
3238 return oss.str();
3239 }
3240 }// namespace construct_string_with_repeat_limit
3241
3242 namespace count_array_pairs_divisible_by_k {
3243 long long Solution::coutPairs(vector<int> &nums, int k) {
3244 long long ans = 0;
3245 // 统计每个数的倍数出现的次数
3246 auto count = unordered_map<int, int>();
3247 for(const auto num: nums) {
3248 count[num]++;
3249 }
3250 const int maximum = *max_element(nums.begin(), nums.end());
3251 // 为什么这个算法是 O(nlnn) 的?因为这个算法的循环次数是 n(1 + 1/2 + 1/3 + ...),由调和级数可知括号内趋向 lnn
3252 for(int i = 1; i <= maximum; i++) {
3253 for(int j = i * 2; j <= maximum; j += i) {
3254 count[i] += count[j];
3255 }
3256 }
3257 for(const auto num: nums) {
3258 // 对于每个数统计与它形成好二元组的数有几个
3259 ans += count[k / gcd(k, num)];
3260 if(static_cast<long long>(num) * num % k == 0) {
3261 // 排除自己和自己形成好二元组的情况
3262 ans--;
3263 }
3264 }
3265 return ans / 2;
3266 }
3267 }// namespace count_array_pairs_divisible_by_k
3268
3269 namespace leetcode717_1_bit_and_2_bit_characters {
3270 bool Solution::isOneBitCharacter(vector<int> &bits) {
3271 for(int i = 0; i < bits.size();) {
3272 int next = i;
3273 if(bits[i] == 1) {
3274 next += 2;
3275 } else {
3276 next += 1;
3277 }
3278 if(next >= bits.size()) {
3279 return i == bits.size() - 1;
3280 }
3281 i = next;
3282 }
3283 return false;
3284 }
3285 }// namespace leetcode717_1_bit_and_2_bit_characters
3286
3287 namespace longest_mountain_in_array {
3288 int Solution::longestMountain(vector<int> &arr) {
3289 if(arr.size() < 3) {
3290 return 0;
3291 }
3292 auto up_down = vector<int>(arr.size() - 1);
3293 for(int i = 0; i + 1 < arr.size(); i++) {
3294 if(arr[i] < arr[i + 1]) {
3295 up_down[i] = 1;
3296 } else if(arr[i] > arr[i + 1]) {
3297 up_down[i] = 0;
3298 } else {
3299 up_down[i] = 2;
3300 }
3301 }
3302 auto sector_size = vector<pair<int, int>>();
3303 int prev = up_down[0];
3304 int count = 1;
3305 for(int i = 1; i < up_down.size(); i++) {
3306 if(up_down[i] != prev) {
3307 sector_size.emplace_back(prev, count);
3308 count = 1;
3309 } else {
3310 count++;
3311 }
3312 prev = up_down[i];
3313 }
3314 sector_size.emplace_back(prev, count);
3315 if(sector_size.size() < 2) {
3316 return 0;
3317 }
3318 int maximum = 0;
3319 for(int i = 0; i + 1 < sector_size.size(); i++) {
3320 if(sector_size[i].first == 1 && sector_size[i + 1].first == 0) {
3321 maximum = max(maximum, sector_size[i].second + sector_size[i + 1].second + 1);
3322 }
3323 }
3324 return maximum;
3325 }
3326 }// namespace longest_mountain_in_array
3327
3328 namespace push_dominoes {
3329 string Solution::pushDominoes(string dominoes) {
3330 const int n = dominoes.length();
3331 auto *left_to_r = new int[n];
3332 auto *right_to_l = new int[n];
3333 auto *left_is = new char[n];
3334 auto *right_is = new char[n];
3335 int l2r = 0;
3336 int r2l = 0;
3337 char ch = '.';
3338 for(int i = 0; i < n; i++) {
3339 if(dominoes[i] != '.') {
3340 ch = dominoes[i];
3341 }
3342 left_is[i] = ch;
3343 }
3344 ch = '.';
3345 for(int i = n - 1; i >= 0; i--) {
3346 if(dominoes[i] != '.') {
3347 ch = dominoes[i];
3348 }
3349 right_is[i] = ch;
3350 }
3351 for(int i = 0; i < n; i++) {
3352 if(dominoes[i] == 'R') {
3353 l2r = 0;
3354 } else {
3355 l2r++;
3356 }
3357 left_to_r[i] = l2r;
3358 }
3359 for(int i = n - 1; i >= 0; i--) {
3360 if(dominoes[i] == 'L') {
3361 r2l = 0;
3362 } else {
3363 r2l++;
3364 }
3365 right_to_l[i] = r2l;
3366 }
3367 for(int i = 0; i < n; i++) {
3368 if(dominoes[i] == '.') {
3369 if(left_is[i] == 'R' && right_is[i] == 'L') {
3370 if(right_to_l[i] > left_to_r[i]) {
3371 dominoes[i] = 'R';
3372 } else if(left_to_r[i] > right_to_l[i]) {
3373 dominoes[i] = 'L';
3374 }
3375 } else if(right_is[i] == 'L') {
3376 dominoes[i] = 'L';
3377 } else if(left_is[i] == 'R') {
3378 dominoes[i] = 'R';
3379 }
3380 }
3381 }
3382 delete[] left_to_r;
3383 delete[] right_to_l;
3384 delete[] left_is;
3385 delete[] right_is;
3386 return dominoes;
3387 }
3388 }// namespace push_dominoes
3389
3390 namespace the_number_of_good_subsets {
3391 int Solution::numberOfGoodSubsets(vector<int> &nums) {
3392 vector<int> freq(num_max + 1);
3393 for(const int num: nums) {
3394 freq[num]++;
3395 }
3396
3397 vector<int> f(mask_max);
3398 f[0] = 1;
3399 for(int i = 0; i < freq[1]; ++i) {
3400 f[0] = f[0] * 2 % mod;
3401 }
3402
3403 for(int i = 2; i <= num_max; ++i) {
3404 if(freq[i] == 0) {
3405 continue;
3406 }
3407
3408 // 检查 i 的每个质因数是否均不超过 1 个
3409 int subset = 0;
3410 const int x = i;
3411 bool check = true;
3412 for(int j = 0; j < primes.size(); j++) {
3413 const int prime = primes[j];
3414 if(x % (prime * prime) == 0) {
3415 check = false;
3416 break;
3417 }
3418 if(x % prime == 0) {
3419 subset |= 1 << j;
3420 }
3421 }
3422 if(!check) {
3423 continue;
3424 }
3425
3426 // 动态规划
3427 for(int mask = mask_max - 1; mask > 0; mask--) {
3428 if((mask & subset) == subset) {
3429 f[mask] = (f[mask] + static_cast<long long>(f[mask ^ subset]) * freq[i]) % mod;
3430 }
3431 }
3432 }
3433 int ans = 0;
3434 for(int mask = 1; mask < mask_max; mask++) {
3435 ans = (ans + f[mask]) % mod;
3436 }
3437 return ans;
3438 }
3439 }// namespace the_number_of_good_subsets
3440
3441 namespace reverse_only_letters {
3443 for(int i = 0, j = s.length() - 1; i < j && i < s.length() && j >= 0;) {
3444 if(isalpha(s[i]) != 0 && isalpha(s[j]) != 0) {
3445 const char temp = s[i];
3446 s[i] = s[j];
3447 s[j] = temp;
3448 i++;
3449 j--;
3450 } else {
3451 while(i < s.length() && isalpha(s[i]) == 0) {
3452 i++;
3453 }
3454 while(j >= 0 && isalpha(s[j]) == 0) {
3455 j--;
3456 }
3457 }
3458 }
3459 return s;
3460 }
3461 }// namespace reverse_only_letters
3462
3463 namespace where_will_the_ball_fall {
3464 vector<int> Solution::findBall(vector<vector<int>> &grid) {
3465 const int m = grid.size();
3466 const int n = grid[0].size();
3467 vector<int> ans(n);
3468 for(int i = 0; i < n; i++) {
3469 int current_x = 0;
3470 int current_y = i;
3471 int dir = 1;// 0 - 左, 1 - 下, 2 - 右
3472 while(true) {
3473 if(current_x == m) {
3474 ans[i] = current_y;
3475 break;
3476 }
3477 if(current_x < 0 || current_y < 0 || current_y >= n) {
3478 ans[i] = -1;
3479 break;
3480 }
3481 if(dir == 0) {
3482 //左
3483 if(grid[current_x][current_y] == 1) {
3484 ans[i] = -1;
3485 break;
3486 }
3487 dir = 1;
3488 } else if(dir == 1) {
3489 //下
3490 if(grid[current_x][current_y] == 1) {
3491 dir = 2;
3492 } else {
3493 dir = 0;
3494 }
3495 } else {
3496 //右
3497 if(grid[current_x][current_y] == 1) {
3498 dir = 1;
3499 } else {
3500 ans[i] = -1;
3501 break;
3502 }
3503 }
3504 if(dir == 0) {
3505 //左
3506 current_y--;
3507 } else if(dir == 1) {
3508 //下
3509 current_x++;
3510 } else {
3511 //右
3512 current_y++;
3513 }
3514 }
3515 }
3516 return ans;
3517 }
3518 }// namespace where_will_the_ball_fall
3519
3520 namespace complex_number_multiplication {
3521 string Solution::complexNumberMultiply(const string &num1, const string &num2) {
3522 auto ss = stringstream();
3523 ss << num1 << num2;
3524 int r1;
3525 int i1;
3526 int r2;
3527 int i2;
3528 ss >> r1;
3529 ss.get();
3530 ss >> i1;
3531 ss.get();
3532 ss >> r2;
3533 ss.get();
3534 ss >> i2;
3535 const int r = r1 * r2 - i1 * i2;
3536 const int i = r1 * i2 + r2 * i1;
3537 ss = stringstream();
3538 ss << r << '+' << i << 'i';
3539 return ss.str();
3540 }
3541 }// namespace complex_number_multiplication
3542
3543 namespace maximum_difference_between_increasing_elements {
3544 int Solution::maximumDifference(vector<int> &nums) {
3545 int minn = nums[0];
3546 int max_diff = -1;
3547 for(int i = 1; i < nums.size(); i++) {
3548 if(nums[i] > minn) {
3549 max_diff = max(max_diff, nums[i] - minn);
3550 }
3551 minn = min(minn, nums[i]);
3552 }
3553 return max_diff;
3554 }
3555 }// namespace maximum_difference_between_increasing_elements
3556
3557 namespace optimal_division {
3558 string Solution::optimalDivision(vector<int> &nums) {
3559 auto oss = ostringstream();
3560 if(nums.size() == 1) {
3561 oss << nums[0];
3562 } else if(nums.size() == 2) {
3563 oss << nums[0] << '/' << nums[1];
3564 } else {
3565 oss << nums[0] << "/(";
3566 for(int i = 1; i < nums.size() - 1; i++) {
3567 oss << nums[i] << '/';
3568 }
3569 oss << nums[nums.size() - 1] << ')';
3570 }
3571 return oss.str();
3572 }
3573 }// namespace optimal_division
3574
3575 namespace counting_words_with_a_given_prefix {
3576 int Solution::prefixCount(vector<string> &words, string pref) {
3577 int ans = 0;
3578 for(auto word: words) {
3579 bool ok = true;
3580 for(int i = 0; i < pref.length(); i++) {
3581 if(pref[i] != word[i]) {
3582 ok = false;
3583 break;
3584 }
3585 }
3586 if(ok) {
3587 ans++;
3588 }
3589 }
3590 return ans;
3591 }
3592 }// namespace counting_words_with_a_given_prefix
3593
3594 namespace minimum_number_of_steps_to_make_two_strings_anagram_ii {
3595 int Solution::minSteps(const string &s, const string &t) {
3596 int ans = 0;
3597 int s_num[26] = {};
3598 int t_num[26] = {};
3599 for(const char ch: s) {
3600 s_num[ch - 'a']++;
3601 }
3602 for(const char ch: t) {
3603 t_num[ch - 'a']++;
3604 }
3605 for(int i = 0; i < 26; i++) {
3606 ans += abs(s_num[i] - t_num[i]);
3607 }
3608 return ans;
3609 }
3610 }// namespace minimum_number_of_steps_to_make_two_strings_anagram_ii
3611
3612 namespace minimum_time_to_complete_trips {
3613 long long Solution::minimumTime(vector<int> &time, int totalTrips) {
3614 int max_t = 1;
3615 int min_t = 100000;
3616 for(auto t: time) {
3617 max_t = max(max_t, t);
3618 min_t = min(min_t, t);
3619 }
3620 long long l = static_cast<long long>(totalTrips) / max_t / time.size();
3621 long long r = static_cast<long long>(totalTrips) * max_t;
3622 while(l <= r) {
3623 const long long m = (l + r) / 2;
3624 long long sum = 0;
3625 for(const auto t: time) {
3626 sum += m / t;
3627 }
3628 if(l == r || l + 1 == r) {
3629 return r;
3630 }
3631 if(sum >= totalTrips) {
3632 r = m;
3633 } else if(sum < totalTrips) {
3634 l = m;
3635 }
3636 }
3637 return 0;
3638 }
3639 }// namespace minimum_time_to_complete_trips
3640
3641 namespace minimum_time_to_finish_the_race {
3642 int Solution::minimumFinishTime(vector<vector<int>> &tires, int changeTime, int numLaps) {
3643 /* min_times[i] = 用一个轮胎跑 i 圈的最小花费 */
3644 vector<long long> min_times(20, 1e9);
3645 for(auto &v: tires) {
3646 const long long f = v[0];
3647 const long long r = v[1];
3648 const long long cost = f + changeTime;
3649 long long current = f;
3650 long long sum = cost;
3651 for(int i = 1; i <= 19; i++) {
3652 min_times[i] = min(min_times[i], sum);
3653 current *= r;
3654 if(current > cost) {
3655 current = f;
3656 sum += cost;
3657 } else {
3658 sum += current;
3659 }
3660 }
3661 }
3662 /* dp[i] = 跑 i 圈的最小花费 */
3663 vector<long long> dp(numLaps + 1, 1e9);
3664 dp[0] = 0;
3665 for(int i = 1; i <= numLaps; i++) {
3666 for(int j = 1; j <= min(19, i); j++) {
3667 dp[i] = min(dp[i], dp[i - j] + min_times[j]);
3668 }
3669 }
3670 /* 最后需要减去一次换轮胎的时间 */
3671 return dp[numLaps] - changeTime;
3672 }
3673 }// namespace minimum_time_to_finish_the_race
3674
3675 namespace maximum_number_of_achievable_transfer_requests {
3676 int Solution::maximumRequests(int n, vector<vector<int>> &requests) {
3677 int ans = 0;
3678 for(unsigned int i = 0; i < 1 << requests.size(); i++) {
3679 auto *in = new int[n];
3680 auto *out = new int[n];
3681 memset(in, 0, n * sizeof(int));
3682 memset(out, 0, n * sizeof(int));
3683 for(unsigned int j = 0; j < requests.size(); j++) {
3684 if((i & 1 << j) != 0) {
3685 out[requests[j][0]]++;
3686 in[requests[j][1]]++;
3687 }
3688 }
3689 bool ok = true;
3690 for(int j = 0; j < n; j++) {
3691 if(out[j] != in[j]) {
3692 ok = false;
3693 break;
3694 }
3695 }
3696 if(ok) {
3697 ans = max(ans, popcount(i));
3698 }
3699 delete[] in;
3700 delete[] out;
3701 }
3702 return ans;
3703 }
3704 }// namespace maximum_number_of_achievable_transfer_requests
3705
3706 namespace zigzag_conversion {
3707 string Solution::convert(string s, int numRows) {
3708 if(numRows == 1) {
3709 return s;
3710 }
3711 auto oss = ostringstream();
3712 auto *m = new char *[numRows];
3713 for(int i = 0; i < numRows; i++) {
3714 m[i] = new char[s.length()];
3715 memset(m[i], ' ', s.length() * sizeof(char));
3716 }
3717 int current_x = 0;
3718 int current_y = 0;
3719 bool dir = true;// true = 下, false = 斜
3720 for(const char ch: s) {
3721 m[current_x][current_y] = ch;
3722 if(dir && current_x == numRows - 1 || !dir && current_x == 0) {
3723 dir = !dir;
3724 }
3725 if(dir) {
3726 current_x++;
3727 } else {
3728 current_x--;
3729 current_y++;
3730 }
3731 }
3732 for(int i = 0; i < numRows; i++) {
3733 for(int j = 0; j <= min(current_y, static_cast<int>(s.length() - 1)); j++) {
3734 if(m[i][j] != ' ') {
3735 oss << m[i][j];
3736 }
3737 }
3738 }
3739 for(int i = 0; i < numRows; i++) {
3740 delete[] m[i];
3741 }
3742 delete[] m;
3743 return oss.str();
3744 }
3745 }// namespace zigzag_conversion
3746
3747 namespace find_the_closest_palindrome {
3748 string Solution::nearestPalindromic(const string &n) {
3749 const long long num = stoll(n);
3750 if(num == 10 || num == 11) {
3751 return "9";
3752 }
3753 if(num < 10) {
3754 return to_string(num - 1);
3755 }
3756 int len = n.length();
3757 const bool even = n.length() % 2 == 0;
3758 string prefix = n.substr(0, n.length() / 2 + (even ? 0 : 1));
3759 string option_str[3];
3760 auto rev = string(prefix.rbegin() + (even ? 0 : 1), prefix.rend());
3761 option_str[2] = prefix + rev;
3762 const long long prefix_int[2] = {stoll(prefix) - 1, stoll(prefix) + 1};
3763 string prefix_str[2] = {to_string(prefix_int[0]), to_string(prefix_int[1])};
3764 for(int i = 0; i < 2; i++) {
3765 if(prefix_str[i].length() == prefix.length()) {
3766 rev = string(prefix_str[i].rbegin() + (even ? 0 : 1), prefix_str[i].rend());
3767 option_str[i] = prefix_str[i] + rev;
3768 } else if(prefix_str[i].length() > prefix.length()) {
3769 rev = string(prefix_str[i].rbegin() + (even ? 1 : 2), prefix_str[i].rend());
3770 option_str[i] = prefix_str[i] + rev;
3771 } else if(prefix_str[i].length() < prefix.length()) {
3772 rev = string(prefix_str[i].rbegin(), prefix_str[i].rend());
3773 option_str[i] = prefix_str[i] + (even ? "9" : "") + rev;
3774 }
3775 }
3776 long long option_int[3] = {stoll(option_str[0]), stoll(option_str[1]), stoll(option_str[2])};
3777 sort(option_int, option_int + 3);
3778 long long minimum = option_int[0];
3779 for(int i = 1; i < 3; i++) {
3780 if(abs(option_int[i] - num) < abs(minimum - num) && option_int[i] != num) {
3781 minimum = option_int[i];
3782 }
3783 }
3784 return to_string(minimum);
3785 }
3786 }// namespace find_the_closest_palindrome
3787
3788 namespace add_digits {
3789 int Solution::addDigits(int num) { return (num - 1) % 9 + 1; }
3790 }// namespace add_digits
3791
3792 namespace sum_of_subarray_ranges {
3793 long long Solution::subArrayRanges(vector<int> &nums) {
3794 long long ans = 0;
3795 for(int i = 0; i + 1 < nums.size(); i++) {
3796 int minimum = nums[i];
3797 int maximum = nums[i];
3798 for(int j = i + 1; j < nums.size(); j++) {
3799 minimum = min(minimum, nums[j]);
3800 maximum = max(maximum, nums[j]);
3801 ans += maximum - minimum;
3802 }
3803 }
3804 return ans;
3805 }
3806 }// namespace sum_of_subarray_ranges
3807
3808 namespace longest_uncommon_subsequence_i {
3809 int Solution::findLUSlength(const string &a, const string &b) {
3810 if(a.length() != b.length() || b.find(a) == string::npos && a.find(b) == string::npos) {
3811 return max(a.length(), b.length());
3812 }
3813 return -1;
3814 }
3815 }// namespace longest_uncommon_subsequence_i
3816
3817 namespace most_frequent_number_following_key_in_an_array {
3818 int Solution::mostFrequent(vector<int> &nums, int key) {
3819 unordered_map<int, int> um;
3820 for(int i = 0; i + 1 < nums.size(); i++) {
3821 if(nums[i] == key) {
3822 um[nums[i + 1]]++;
3823 }
3824 }
3825 int max_v = 0;
3826 int max_k = 0;
3827 for(auto [k, v]: um) {
3828 if(v > max_v) {
3829 max_v = v;
3830 max_k = k;
3831 }
3832 }
3833 return max_k;
3834 }
3835 }// namespace most_frequent_number_following_key_in_an_array
3836
3837 namespace sort_the_jumbled_numbers {
3838 vector<int> Solution::sortJumbled(vector<int> &mapping, vector<int> &nums) {
3839 vector<tuple<int, int, int>> vec;
3840 for(int i = 0; i < nums.size(); i++) {
3841 string str = to_string(nums[i]);
3842 ostringstream oss;
3843 for(const char ch: str) {
3844 oss << mapping[ch - '0'];
3845 }
3846 vec.emplace_back(i, nums[i], stoi(oss.str()));
3847 }
3848 sort(vec.begin(), vec.end(), cmp());
3849 vector<int> ans;
3850 ans.reserve(vec.size());
3851 for(auto [i, num, rev]: vec) {
3852 ans.push_back(num);
3853 }
3854 return ans;
3855 }
3856 }// namespace sort_the_jumbled_numbers
3857
3858 namespace all_ancestors_of_a_node_in_a_directed_acyclic_graph {
3859 vector<vector<int>> Solution::getAncestors(int n, vector<vector<int>> &edges) {
3860 for(int i = 0; i < n; i++) {
3861 nexts[i] = unordered_set<int>();
3862 ancestors[i] = set<int>();
3863 }
3864 for(auto edge: edges) {
3865 nexts[edge[0]].insert(edge[1]);
3866 }
3867 for(int i = 0; i < n; i++) {
3868 for(const auto next: nexts[i]) {
3869 auto *dfsd = new bool[n];
3870 memset(dfsd, 0, n * sizeof(bool));
3871 dfs(dfsd, i, next);
3872 delete[] dfsd;
3873 }
3874 }
3875 vector<vector<int>> ans;
3876 for(int i = 0; i < n; i++) {
3877 vector<int> vec;
3878 for(auto i: ancestors[i]) {
3879 vec.push_back(i);
3880 }
3881 ans.push_back(vec);
3882 }
3883 return ans;
3884 }
3885
3886 void Solution::dfs(bool *dfsd, int v, int i) {
3887 ancestors[i].insert(v);
3888 dfsd[i] = true;
3889 for(const auto next: nexts[i]) {
3890 if(!dfsd[next]) {
3891 dfs(dfsd, v, next);
3892 }
3893 }
3894 }
3895 }// namespace all_ancestors_of_a_node_in_a_directed_acyclic_graph
3896
3897 namespace minimum_number_of_moves_to_make_palindrome {
3899 int ans = 0;
3900 for(int left = 0, right = s.size() - 1; left < right; left++) {
3901 bool even = false;
3902 for(int i = right; left != i; i--) {
3903 if(s[left] == s[i]) {
3904 even = true;
3905 // 字母出现偶数次的情况,模拟交换
3906 for(; i < right; i++) {
3907 swap(s[i], s[i + 1]);
3908 ans++;
3909 }
3910 right--;
3911 break;
3912 }
3913 }
3914 if(!even) {
3915 // 字母出现奇数次的情况,计算它距离中间还有多少距离
3916 ans += s.size() / 2 - left;
3917 }
3918 }
3919 return ans;
3920 }
3921 }// namespace minimum_number_of_moves_to_make_palindrome
3922
3923 namespace cells_in_a_range_on_an_excel_sheet {
3924 vector<string> Solution::cellsInRange(const string &s) {
3925 vector<string> ans;
3926 istringstream ss(s);
3927 char col1;
3928 char col2;
3929 int row1;
3930 int row2;
3931 ss >> col1 >> row1;
3932 ss.get();
3933 ss >> col2 >> row2;
3934 for(char col = col1; col <= col2; col++) {
3935 for(int row = row1; row <= row2; row++) {
3936 ostringstream oss;
3937 oss << col << row;
3938 ans.push_back(oss.str());
3939 }
3940 }
3941 return ans;
3942 }
3943 }// namespace cells_in_a_range_on_an_excel_sheet
3944
3945 namespace append_k_integers_with_minimal_sum {
3946 long long Solution::minimalKSum(vector<int> &nums, int k) {
3947 long long ans = 0;
3948 set<int> s;
3949 for(auto num: nums) {
3950 s.insert(num);
3951 }
3952 long long limit = k;
3953 for(auto i = s.begin(); i != s.end() && *i <= limit; ++i) {
3954 limit++;
3955 }
3956 ans += limit + limit * (limit - 1) / 2;
3957 for(auto i = s.begin(); i != s.end() && *i < limit; ++i) {
3958 ans -= *i;
3959 }
3960 return ans;
3961 }
3962 }// namespace append_k_integers_with_minimal_sum
3963
3964 namespace create_binary_tree_from_descriptions {
3965 TreeNode *Solution::createBinaryTree(vector<vector<int>> &descriptions) {
3966 unordered_map<int, TreeNode *> um;
3967 unordered_set<int> nodes;
3968 unordered_set<int> childs;
3969 for(auto description: descriptions) {
3970 nodes.insert(description[0]);
3971 nodes.insert(description[1]);
3972 childs.insert(description[1]);
3973 }
3974 for(auto node: nodes) {
3975 um[node] = new TreeNode();
3976 }
3977 for(auto description: descriptions) {
3978 if(description[2] == 1) {
3979 //childi 是 parenti 的左子节点
3980 um[description[0]]->left = um[description[1]];
3981 } else {
3982 //childi 是 parenti 的右子节点。
3983 um[description[0]]->right = um[description[1]];
3984 }
3985 }
3986 for(auto node: nodes) {
3987 if(!childs.contains(node)) {
3988 return um[node];
3989 }
3990 }
3991 return nullptr;
3992 }
3993 }// namespace create_binary_tree_from_descriptions
3994
3995 namespace replace_non_coprime_numbers_in_array {
3996 vector<int> Solution::replaceNonCoprimes(vector<int> &nums) {
3997 vector<int> ans;
3998 for(int i = 0; i < nums.size(); i++) {
3999 int num = nums[i];
4000 while(!ans.empty() && gcd(num, ans.back()) > 1) {
4001 num = num / gcd(num, ans.back()) * ans.back();
4002 ans.pop_back();
4003 }
4004 ans.push_back(num);
4005 }
4006 return ans;
4007 }
4008 }// namespace replace_non_coprime_numbers_in_array
4009
4010 namespace find_good_days_to_rob_the_bank {
4011 vector<int> Solution::goodDaysToRobBank(vector<int> &security, int time) {
4012 if(security.size() < 2 * time + 1) {
4013 return {};
4014 }
4015 vector<int> ans;
4016 if(time == 0) {
4017 for(int i = 0; i < security.size(); i++) {
4018 ans.push_back(i);
4019 }
4020 return ans;
4021 }
4022 vector non_increasing(security.size(), 0);
4023 vector non_decreasing(security.size(), 0);
4024 for(int i = 1; i < security.size(); i++) {
4025 if(security[i] >= security[i - 1]) {
4026 non_decreasing[i] = non_decreasing[i - 1] + 1;
4027 } else {
4028 non_decreasing[i] = 0;
4029 }
4030 if(security[i] <= security[i - 1]) {
4031 non_increasing[i] = non_increasing[i - 1] + 1;
4032 } else {
4033 non_increasing[i] = 0;
4034 }
4035 }
4036 for(int i = time; i + time < security.size(); i++) {
4037 if(non_decreasing[i + time] >= time && non_increasing[i] >= time) {
4038 ans.push_back(i);
4039 }
4040 }
4041 return ans;
4042 }
4043 }// namespace find_good_days_to_rob_the_bank
4044
4045 namespace base_7 {
4047 bool pos = true;
4048 if(num < 0) {
4049 pos = false;
4050 num = -num;
4051 }
4052 if(num == 0) {
4053 return "0";
4054 }
4055 deque<int> deq;
4056 while(num != 0) {
4057 deq.push_front(num % 7);
4058 num /= 7;
4059 }
4060 ostringstream oss;
4061 if(!pos) {
4062 oss << '-';
4063 }
4064 for(const int n: deq) {
4065 oss << n;
4066 }
4067 return oss.str();
4068 }
4069 }// namespace base_7
4070
4071 namespace plates_between_candles {
4072 vector<int> Solution::platesBetweenCandles(string s, vector<vector<int>> &queries) {
4073 vector<int> ans;
4074 vector<int> plate_count(s.length());
4075 vector<int> candle_pos;
4076 if(s[0] == '*') {
4077 plate_count[0] = 1;
4078 } else {
4079 plate_count[0] = 0;
4080 candle_pos.push_back(0);
4081 }
4082 for(int i = 1; i < s.length(); i++) {
4083 plate_count[i] = plate_count[i - 1];
4084 if(s[i] == '*') {
4085 plate_count[i]++;
4086 } else {
4087 candle_pos.push_back(i);
4088 }
4089 }
4090 for(auto query: queries) {
4091 int left = query[0];
4092 int right = query[1];
4093 auto li = lower_bound(candle_pos.begin(), candle_pos.end(), left);
4094 if(li == candle_pos.end() || *li > right) {
4095 ans.push_back(0);
4096 continue;
4097 }
4098 auto ri = lower_bound(candle_pos.rbegin(), candle_pos.rend(), right, greater<int>());
4099 if(ri == candle_pos.rend() || *ri < left) {
4100 ans.push_back(0);
4101 continue;
4102 }
4103 ans.push_back(plate_count[*ri] - plate_count[*li]);
4104 }
4105 return ans;
4106 }
4107 }// namespace plates_between_candles
4108
4109 namespace smallest_rotation_with_highest_score {
4110 int Solution::bestRotation(vector<int> &nums) {
4111 const int n = nums.size();
4112 vector k_score_diff(n + 1, 0);
4113 for(int i = 0; i < n; i++) {
4114 const int low = (i + 1) % n;
4115 const int high = (i - nums[i] + n) % n;
4116 k_score_diff[low]++;
4117 k_score_diff[high + 1]--;
4118 if(low > high) {
4119 k_score_diff[0]++;
4120 k_score_diff[n]--;
4121 }
4122 }
4123 int ans = 0;
4124 int max_score = 0;
4125 int score = 0;
4126 for(int i = 0; i < n; i++) {
4127 score += k_score_diff[i];
4128 if(score > max_score) {
4129 ans = i;
4130 max_score = score;
4131 }
4132 }
4133 return ans;
4134 }
4135 }// namespace smallest_rotation_with_highest_score
4136
4137 namespace n_ary_tree_preorder_traversal {
4139 if(root == nullptr) {
4140 return {};
4141 }
4142 vector<int> ans;
4143 ans.push_back(root->val);
4144 for(auto *child: root->children) {
4145 auto preorder_child = preorder(child);
4146 ans.insert(ans.end(), preorder_child.begin(), preorder_child.end());
4147 }
4148 return ans;
4149 }
4150 }// namespace n_ary_tree_preorder_traversal
4151
4152 namespace count_nodes_with_the_highest_score {
4153 int Solution::countHighestScoreNodes(vector<int> &parents) {
4154 int ans = 0;
4155 auto nodes = vector<TreeNode *>(parents.size(), nullptr);
4156 auto edges = vector(parents.size(), vector<int>());
4157 auto scores = vector<unsigned long long>(parents.size(), 0);
4158 for(int i = 0; i < parents.size(); i++) {
4159 nodes[i] = new TreeNode(i);
4160 if(parents[i] != -1) {
4161 edges[i].push_back(parents[i]);
4162 edges[parents[i]].push_back(i);
4163 }
4164 }
4165 TreeNode *root = nullptr;
4166 for(int i = 0; i < parents.size(); i++) {
4167 if(parents[i] != -1) {
4168 nodes[parents[i]]->add_child(nodes[i]);
4169 } else {
4170 root = nodes[i];
4171 }
4172 }
4173 root->dfs();
4174 unsigned long long max_score = 0;
4175 for(int i = 0; i < parents.size(); i++) {
4176 unsigned long long score = 1;
4177 const auto *node = nodes[i];
4178 for(const auto *child: node->get_children()) {
4179 score *= child->get_count();
4180 }
4181 if(node->get_parent() != nullptr) {
4182 score *= root->get_count() - node->get_count();
4183 }
4184 max_score = max(max_score, score);
4185 scores[i] = score;
4186 }
4187 return count(scores.begin(), scores.end(), max_score);
4188 }
4189
4191 this->children.push_back(node);
4192 node->parent = this;
4193 }
4194
4196 int ans = 1;
4197 for(auto *child: this->children) {
4198 ans += child->dfs();
4199 }
4200 this->count = ans;
4201 return ans;
4202 }
4203
4204 const vector<TreeNode *> &TreeNode::get_children() const { return children; }
4205
4206 int TreeNode::get_count() const { return count; }
4207
4209 }// namespace count_nodes_with_the_highest_score
4210
4211 namespace n_ary_tree_postorder_traversal {
4213 if(root == nullptr) {
4214 return {};
4215 }
4216 vector<int> ans;
4217 for(auto *child: root->children) {
4218 auto res = postorder(child);
4219 ans.insert(ans.end(), res.begin(), res.end());
4220 }
4221 ans.push_back(root->val);
4222 return ans;
4223 }
4224 }// namespace n_ary_tree_postorder_traversal
4225
4226 namespace max_area_of_island {
4227 int Solution::maxAreaOfIsland(vector<vector<int>> &grid) {
4228 const int m = grid.size();
4229 const int n = grid[0].size();
4230 auto uf = UnionFind(m, n);
4231 int ans = 0;
4232 for(int i = 0; i < m; i++) {
4233 for(int j = 0; j < n; j++) {
4234 if(grid[i][j] == 1) {
4235 const pair<int, int> p = make_pair(i, j);
4236 ans = max(ans, uf.get_size(p));
4237 pair<int, int> siblings[4] = {
4238 make_pair(i + 1, j),
4239 make_pair(i - 1, j),
4240 make_pair(i, j + 1),
4241 make_pair(i, j - 1),
4242 };
4243 for(const auto sibling: siblings) {
4244 if(uf.contains(sibling) && grid[sibling.first][sibling.second] == 1 && !uf.same(p, sibling)) {
4245 uf.merge(p, sibling);
4246 ans = max(ans, uf.get_size(p));
4247 }
4248 }
4249 }
4250 }
4251 }
4252 return ans;
4253 }
4254
4256 : m(m), n(n) {
4257 parent = unordered_map<pair<int, int>,
4258 pair<int, int>,
4259 function<unsigned int(const pair<int, int> &)>>(
4260 m * n,
4261 [](const pair<int, int> &p) { return static_cast<unsigned int>(p.first * 50 + p.second); });
4262 size = unordered_map<pair<int, int>,
4263 int,
4264 function<unsigned int(const pair<int, int> &)>>(
4265 m * n,
4266 [](const pair<int, int> &p) { return static_cast<unsigned int>(p.first * 50 + p.second); });
4267 rank = unordered_map<pair<int, int>,
4268 int,
4269 function<unsigned int(const pair<int, int> &)>>(
4270 m * n,
4271 [](const pair<int, int> &p) { return static_cast<unsigned int>(p.first * 50 + p.second); });
4272 for(int i = 0; i < m; i++) {
4273 for(int j = 0; j < n; j++) {
4274 pair<int, int> p = make_pair(i, j);
4275 parent[p] = p;
4276 size[p] = 1;
4277 rank[p] = 0;
4278 }
4279 }
4280 }
4281
4282 pair<int, int> UnionFind::find(pair<int, int> val) {
4283 if(parent[val] != val) {
4284 parent[val] = find(parent[val]);
4285 }
4286 return parent[val];
4287 }
4288
4289 void UnionFind::merge(pair<int, int> a, pair<int, int> b) {
4290 const auto pa = find(a);
4291 const auto pb = find(b);
4292 if(pa != pb) {
4293 const int sum = size[pa] + size[pb];
4294 if(rank[pa] > rank[pb]) {
4295 parent[pb] = pa;
4296 } else {
4297 parent[pa] = pb;
4298 if(rank[pa] == rank[pb]) {
4299 ++rank[pb];
4300 }
4301 }
4302 size[pa] = sum;
4303 size[pb] = sum;
4304 }
4305 }
4306
4307 bool UnionFind::same(pair<int, int> a, pair<int, int> b) { return find(a) == find(b); }
4308
4309 bool UnionFind::contains(pair<int, int> p) const { return parent.contains(p); }
4310
4311 int UnionFind::get_size(pair<int, int> p) { return size[find(p)]; }
4312 }// namespace max_area_of_island
4313
4314 namespace find_all_k_distant_indices_in_an_array {
4315 vector<int> Solution::findKDistantIndices(vector<int> &nums, int key, int k) {
4316 set<int> key_set;
4317 set<int> ans_set;
4318 for(int i = 0; i < nums.size(); i++) {
4319 if(nums[i] == key) {
4320 key_set.insert(i);
4321 }
4322 }
4323 for(const auto ks: key_set) {
4324 for(int i = ks - k; i <= ks + k; i++) {
4325 if(0 <= i && i < nums.size()) {
4326 ans_set.insert(i);
4327 }
4328 }
4329 }
4330 return vector(ans_set.begin(), ans_set.end());
4331 }
4332 }// namespace find_all_k_distant_indices_in_an_array
4333
4334 namespace count_artifacts_that_can_be_extracted {
4335 int Solution::digArtifacts(int n, vector<vector<int>> &artifacts, vector<vector<int>> &dig) {
4336 auto *grid = new bool *[n];
4337 for(int i = 0; i < n; i++) {
4338 grid[i] = new bool[n];
4339 memset(grid[i], 0, n * sizeof(bool));
4340 }
4341 for(auto i: dig) {
4342 grid[i[0]][i[1]] = true;
4343 }
4344 int ans = 0;
4345 for(auto artifact: artifacts) {
4346 bool flag = true;
4347 for(int i = artifact[0]; i <= artifact[2]; i++) {
4348 for(int j = artifact[1]; j <= artifact[3]; j++) {
4349 if(!grid[i][j]) {
4350 flag = false;
4351 break;
4352 }
4353 }
4354 if(!flag) {
4355 break;
4356 }
4357 }
4358 if(flag) {
4359 ans++;
4360 }
4361 }
4362 for(int i = 0; i < n; i++) {
4363 delete[] grid[i];
4364 }
4365 delete[] grid;
4366 return ans;
4367 }
4368 }// namespace count_artifacts_that_can_be_extracted
4369
4370 namespace maximize_the_topmost_element_after_k_moves {
4371 int Solution::maximumTop(vector<int> &nums, int k) {
4372 if(nums.size() == 1 && k % 2 == 1) {
4373 return -1;
4374 }
4375 if(k > nums.size()) {
4376 int ans = -1;
4377 for(auto num: nums) {
4378 ans = max(ans, num);
4379 }
4380 return ans;
4381 }
4382 unordered_map<int, int> element_count;
4383 set<int> poped_elements;
4384 for(auto num: nums) {
4385 element_count[num]++;
4386 }
4387 for(int i = 0; i < nums.size() && i < k - 1; i++) {
4388 poped_elements.insert(nums[i]);
4389 element_count[nums[i]]--;
4390 }
4391 int ans = -1;
4392 if(k < nums.size()) {
4393 ans = nums[k];
4394 }
4395 int maximum = -1;
4396 for(const auto i = poped_elements.rbegin(); i != poped_elements.rend();) {
4397 maximum = *i;
4398 break;
4399 }
4400 return max(ans, maximum);
4401 }
4402 }// namespace maximize_the_topmost_element_after_k_moves
4403
4404 namespace minimum_weighted_subgraph_with_the_required_paths {
4405 long long Solution::minimumWeight(int n, vector<vector<int>> &edges, int src1, int src2, int dest) {
4406 auto *graph = new vector<pair<int, int>>[n];
4407 auto *graph_rev = new vector<pair<int, int>>[n];
4408 for(int i = 0; i < n; i++) {
4409 graph[i] = vector<pair<int, int>>();
4410 graph_rev[i] = vector<pair<int, int>>();
4411 }
4412 for(auto &edge: edges) {
4413 auto from = edge[0];
4414 auto to = edge[1];
4415 auto weight = edge[2];
4416 graph[from].emplace_back(to, weight);
4417 graph_rev[to].emplace_back(from, weight);
4418 }
4419
4420 long long a = LLONG_MAX;
4421 vector dist_src1(n, LLONG_MAX);
4422 vector dist_src2(n, LLONG_MAX);
4423 vector dist_dest(n, LLONG_MAX);
4424
4425 calc_dist(src1, graph, dist_src1);
4426 calc_dist(src2, graph, dist_src2);
4427 calc_dist(dest, graph_rev, dist_dest);
4428
4429 long long ans = LLONG_MAX;
4430
4431 for(int i = 0; i < n; ++i) {
4432 if(dist_src1[i] != LLONG_MAX && dist_src2[i] != LLONG_MAX && dist_dest[i] != LLONG_MAX) {
4433 ans = min(ans, dist_src1[i] + dist_src2[i] + dist_dest[i]);
4434 }
4435 }
4436 if(ans == LLONG_MAX) {
4437 ans = -1;
4438 }
4439 delete[] graph;
4440 delete[] graph_rev;
4441 return ans;
4442 }
4443
4444 void Solution::calc_dist(int s, vector<pair<int, int>> *graph, vector<long long int> &dist) {
4445 priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
4446 dist[s] = 0;
4447 pq.emplace(0, s);
4448 while(!pq.empty()) {
4449 auto [weight, node] = pq.top();
4450 pq.pop();
4451 if(weight > dist[node]) {
4452 continue;
4453 }
4454 for(auto [next_node, next_weight]: graph[node]) {
4455 if(weight + next_weight < dist[next_node]) {
4456 dist[next_node] = weight + next_weight;
4457 pq.emplace(weight + next_weight, next_node);
4458 }
4459 }
4460 }
4461 }
4462 }// namespace minimum_weighted_subgraph_with_the_required_paths
4463
4464 namespace utf_8_validation {
4465 bool Solution::validUtf8(vector<int> &data) {
4466 vector<int> len;
4467 for(const auto num: data) {
4468 if(num >> 7 == 0) {
4469 //0xxxxxxx
4470 len.push_back(1);
4471 } else if(num >> 3 == 30) {
4472 //11110xxx
4473 len.push_back(4);
4474 } else if(num >> 4 == 14) {
4475 //1110xxxx
4476 len.push_back(3);
4477 } else if(num >> 5 == 6) {
4478 //110xxxxx
4479 len.push_back(2);
4480 } else if(num >> 6 == 2) {
4481 //10xxxxxx
4482 len.push_back(-1);
4483 } else {
4484 return false;
4485 }
4486 }
4487 int count = 0;
4488 for(int i = 0; i < len.size(); i++) {
4489 if(count != 0) {
4490 if(len[i] != -1) {
4491 return false;
4492 }
4493 } else {
4494 count = len[i];
4495 if(count == -1) {
4496 return false;
4497 }
4498 }
4499 count--;
4500 }
4501 return count == 0;
4502 }
4503 }// namespace utf_8_validation
4504
4505 namespace minimum_index_sum_of_two_lists {
4506 vector<string> Solution::findRestaurant(vector<string> &list1, vector<string> &list2) {
4507 unordered_map<string, int> restaurants;
4508 unordered_map<string, int> index1;
4509 unordered_map<string, int> index2;
4510 for(int i = 0; i < list1.size(); i++) {
4511 restaurants[list1[i]]++;
4512 index1[list1[i]] = i;
4513 }
4514 for(int i = 0; i < list2.size(); i++) {
4515 restaurants[list2[i]]++;
4516 index2[list2[i]] = i;
4517 }
4518 unordered_set<string> optional_restaurants;
4519 for(auto [restaurant, count]: restaurants) {
4520 if(count > 1) {
4521 optional_restaurants.insert(restaurant);
4522 }
4523 }
4524 int min_index_sum = INT_MAX;
4525 for(const auto &optional_restaurant: optional_restaurants) {
4526 int index_sum = index1[optional_restaurant] + index2[optional_restaurant];
4527 min_index_sum = min(min_index_sum, index_sum);
4528 }
4529 vector<string> ans;
4530 for(const auto &optional_restaurant: optional_restaurants) {
4531 int index_sum = index1[optional_restaurant] + index2[optional_restaurant];
4532 if(index_sum == min_index_sum) {
4533 ans.push_back(optional_restaurant);
4534 }
4535 }
4536 return ans;
4537 }
4538 }// namespace minimum_index_sum_of_two_lists
4539
4540 namespace count_number_of_maximum_bitwise_or_subsets {
4541 int Solution::countMaxOrSubsets(vector<int> &nums) {
4542 int max = 0;
4543 for(const auto num: nums) {
4544 max |= num;
4545 }
4546 return dfs(0, max, nums);
4547 }
4548
4549 int Solution::dfs(int current, int target, vector<int> nums) {
4550 if((current | target) == current) {
4551 return 1 << nums.size();
4552 }
4553 int sum = 0;
4554 vector nums_cpy = nums;
4555 for(int i = 0; i < nums.size(); i++) {
4556 nums_cpy.erase(nums_cpy.begin());
4557 sum += dfs(current | nums[i], target, nums_cpy);
4558 }
4559 return sum;
4560 }
4561 }// namespace count_number_of_maximum_bitwise_or_subsets
4562
4563 namespace all_oone_data_structure {
4565 str_count = unordered_map<string, int>();
4566 count_str = map<int, unordered_set<string>>();
4567 }
4568
4569 void AllOne::inc(const string &key) {
4570 const int prev = str_count[key]++;
4571 count_str[prev].erase(key);
4572 count_str[prev + 1].insert(key);
4573 if(count_str[prev].empty()) {
4574 count_str.erase(prev);
4575 }
4576 if(!count_str.empty()) {
4577 min = count_str.begin()->first;
4578 max = count_str.rbegin()->first;
4579 } else {
4580 min = 50000;
4581 max = 0;
4582 }
4583 }
4584
4585 void AllOne::dec(const string &key) {
4586 const int prev = str_count[key]--;
4587 if(str_count[key] == 0) {
4588 str_count.erase(key);
4589 }
4590 count_str[prev].erase(key);
4591 if(count_str[prev].empty()) {
4592 count_str.erase(prev);
4593 }
4594 if(prev != 1) {
4595 count_str[prev - 1].insert(key);
4596 }
4597 if(!count_str.empty()) {
4598 min = count_str.begin()->first;
4599 max = count_str.rbegin()->first;
4600 } else {
4601 min = 50000;
4602 max = 0;
4603 }
4604 }
4605
4607 if(str_count.empty()) {
4608 return "";
4609 }
4610 return *count_str[max].begin();
4611 }
4612
4614 if(str_count.empty()) {
4615 return "";
4616 }
4617 return *count_str[min].begin();
4618 }
4619 }// namespace all_oone_data_structure
4620
4621 namespace longest_word_in_dictionary {
4622 string Solution::longestWord(vector<string> &words) {
4623 auto root = TrieNode('0');
4624 for(const auto &word: words) {
4625 root.insert(word);
4626 }
4627 return dfs("", &root);
4628 }
4629
4630 string Solution::dfs(const string &str, TrieNode *node) {
4631 string ans = str;
4632 for(auto *next: node->nexts) {
4633 if(next != nullptr && next->end_of_word) {
4634 string ret = dfs(str + next->ch, next);
4635 if(ans.length() < ret.length()) {
4636 ans = ret;
4637 }
4638 }
4639 }
4640 return ans;
4641 }
4642 }// namespace longest_word_in_dictionary
4643
4644 namespace simple_bank_system {
4645 Bank::Bank(vector<long long int> &balance) {
4646 accounts = unordered_map<int, long long>(balance.size());
4647 for(int i = 0; i < balance.size(); i++) {
4648 accounts[i + 1] = balance[i];
4649 }
4650 }
4651
4652 bool Bank::transfer(int account1, int account2, long long int money) {
4653 if(!accounts.contains(account1) || !accounts.contains(account2)) {
4654 return false;
4655 }
4656 if(accounts[account1] < money) {
4657 return false;
4658 }
4659 accounts[account1] -= money;
4660 accounts[account2] += money;
4661 return true;
4662 }
4663
4664 bool Bank::deposit(int account, long long int money) {
4665 if(!accounts.contains(account)) {
4666 return false;
4667 }
4668 accounts[account] += money;
4669 return true;
4670 }
4671
4672 bool Bank::withdraw(int account, long long int money) {
4673 if(!accounts.contains(account)) {
4674 return false;
4675 }
4676 if(accounts[account] < money) {
4677 return false;
4678 }
4679 accounts[account] -= money;
4680 return true;
4681 }
4682 }// namespace simple_bank_system
4683
4684 namespace construct_string_from_binary_tree {
4686 ostringstream oss;
4687 oss << root->val;
4688 if(root->left != nullptr) {
4689 oss << '(' << tree2str(root->left) << ')';
4690 } else if(root->right != nullptr) {
4691 oss << "()";
4692 }
4693 if(root->right != nullptr) {
4694 oss << '(' << tree2str(root->right) << ')';
4695 }
4696 return oss.str();
4697 }
4698 }// namespace construct_string_from_binary_tree
4699
4700 namespace maximize_number_of_subsequences_in_a_string {
4701 long long Solution::maximumSubsequenceCount(string text, string pattern) {
4702 long long ans = 0;
4703 long long count = 0;
4704 vector<long long> p1count(text.length());
4705 long long p0count = 0;
4706 long long p1c = 0;
4707 p1count[text.length() - 1] = 0;
4708 for(int i = text.length() - 1; i >= 0; i--) {
4709 if(text[i] == pattern[1]) {
4710 count++;
4711 } else if(text[i] == pattern[0]) {
4712 p0count++;
4713 }
4714 if(i - 1 >= 0) {
4715 p1count[i - 1] = count;
4716 }
4717 }
4718 for(int i = 0; i < text.length(); i++) {
4719 if(text[i] == pattern[0]) {
4720 ans += p1count[i];
4721 }
4722 }
4723 ans += max(p0count, count);
4724 return ans;
4725 }
4726 }// namespace maximize_number_of_subsequences_in_a_string
4727
4728 namespace minimum_operations_to_halve_array_sum {
4729 int Solution::halveArray(vector<int> &nums) {
4730 long double sum = 0;
4731 int ans = 0;
4732 priority_queue<long double> pq;
4733 for(const auto num: nums) {
4734 pq.push(num);
4735 sum += num;
4736 }
4737 const long double target = sum / 2;
4738 while(sum > target) {
4739 auto num = pq.top();
4740 pq.pop();
4741 num /= 2;
4742 sum -= num;
4743 pq.push(num);
4744 ans++;
4745 }
4746 return ans;
4747 }
4748 }// namespace minimum_operations_to_halve_array_sum
4749
4750 namespace minimum_white_tiles_after_covering_with_carpets {
4751 int Solution::minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {
4752 const int n = floor.length();
4753 vector f(numCarpets + 1, vector<int>(n));
4754 f[0][0] = floor[0] % 2;
4755 for(int i = 1; i < n; ++i) {
4756 f[0][i] = f[0][i - 1] + floor[i] % 2;
4757 }
4758 for(int i = 1; i <= numCarpets; ++i) {
4759 // j < carpetLen 的 f[i][j] 均为 0
4760 for(int j = carpetLen; j < n; ++j) {
4761 f[i][j] = min(f[i][j - 1] + floor[j] % 2, f[i - 1][j - carpetLen]);
4762 }
4763 }
4764 return f[numCarpets][n - 1];
4765 }
4766 }// namespace minimum_white_tiles_after_covering_with_carpets
4767
4768 namespace count_hills_and_valleys_in_an_array {
4769 int Solution::countHillValley(vector<int> &nums) {
4770 int ans = 0;
4771 const auto u = unique(nums.begin(), nums.end());
4772 nums.erase(u, nums.end());
4773 for(int i = 1; i + 1 < nums.size(); i++) {
4774 if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1] || nums[i] < nums[i - 1] && nums[i] < nums[i + 1]) {
4775 ans++;
4776 }
4777 }
4778 return ans;
4779 }
4780 }// namespace count_hills_and_valleys_in_an_array
4781
4782 namespace count_collisions_on_a_road {
4783 int Solution::countCollisions(const string &directions) {
4784 int ans = 0;
4785 vector<char> status;
4786 vector<int> count;
4787 int current = 0;
4788 for(char ch: directions) {
4789 if(status.empty()) {
4790 status.push_back(ch);
4791 current++;
4792 } else {
4793 if(status.back() == ch) {
4794 current++;
4795 } else {
4796 status.push_back(ch);
4797 count.push_back(current);
4798 current = 1;
4799 }
4800 }
4801 }
4802 count.push_back(current);
4803 for(int i = 0; i + 1 < status.size(); i++) {
4804 if(status[i] == 'R' && status[i + 1] == 'L') {
4805 ans += count[i] + count[i + 1];
4806 } else if(status[i] == 'R' && status[i + 1] == 'S') {
4807 ans += count[i];
4808 } else if(status[i] == 'S' && status[i + 1] == 'L') {
4809 ans += count[i + 1];
4810 }
4811 }
4812 return ans;
4813 }
4814 }// namespace count_collisions_on_a_road
4815
4816 namespace maximum_points_in_an_archery_competition {
4817 vector<int> Solution::maximumBobPoints(int numArrows, vector<int> &aliceArrows) {
4818 int maximum = 0;
4819 int max_n = 0;
4820 for(unsigned int n = 1; n < 1 << 11; n++) {
4821 int rest = numArrows;
4822 int score = 0;
4823 for(int i = 0; i <= 10; i++) {
4824 if((n & 1 << i) != 0) {
4825 score += 11 - i;
4826 rest -= aliceArrows[11 - i] + 1;
4827 }
4828 if(rest < 0) {
4829 goto NEXT_N;
4830 }
4831 }
4832 if(maximum < score) {
4833 maximum = score;
4834 max_n = n;
4835 }
4836 NEXT_N:;
4837 }
4838 vector ans(aliceArrows.size(), 0);
4839 for(int i = 0; i <= 10; i++) {
4840 if((max_n & 1 << i) != 0) {
4841 numArrows -= aliceArrows[11 - i] + 1;
4842 ans[11 - i] = aliceArrows[11 - i] + 1;
4843 }
4844 }
4845 ans[0] += numArrows;
4846 return ans;
4847 }
4848 }// namespace maximum_points_in_an_archery_competition
4849
4850 namespace the_time_when_the_network_becomes_idle {
4851 int Solution::networkBecomesIdle(vector<vector<int>> &edges, vector<int> &patience) {
4852 unordered_map<int, Node *> um;
4853 unordered_set<int> nodes;
4854 for(int i = 0; i < patience.size(); i++) {
4855 um[i] = new Node(i, patience[i]);
4856 nodes.insert(i);
4857 }
4858 for(auto edge: edges) {
4859 um[edge[0]]->linked.insert(edge[1]);
4860 um[edge[1]]->linked.insert(edge[0]);
4861 }
4862 auto comp = [](const pair<int, int> &s1, const pair<int, int> &s2) -> bool { return s1.second > s2.second; };
4863 priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq;
4864 pq.push(make_pair(0, 0));
4865 while(!nodes.empty()) {
4866 auto [num, len] = pq.top();
4867 pq.pop();
4868 if(nodes.contains(num)) {
4869 nodes.erase(num);
4870 Node *node = um[num];
4871 node->time = len;
4872 for(auto next: node->linked) {
4873 if(nodes.contains(next)) {
4874 pq.push(make_pair(next, len + 1));
4875 }
4876 }
4877 }
4878 }
4879 int ans = 0;
4880 for(auto [num, node]: um) {
4881 if(num != 0) {
4882 int resent_num = node->time * 2 / node->patience;
4883 if(node->time * 2 % node->patience == 0) {
4884 resent_num--;
4885 }
4886 ans = max(ans, resent_num * node->patience + 2 * node->time + 1);
4887 }
4888 }
4889 return ans;
4890 }
4891 }// namespace the_time_when_the_network_becomes_idle
4892
4893 namespace two_sum_iv_input_is_a_bst {
4895 set<int> s;
4896 unordered_map<int, int> count;
4897 queue<TreeNode *> que;
4898 que.push(root);
4899 while(!que.empty()) {
4900 const auto *node = que.front();
4901 que.pop();
4902 s.insert(node->val);
4903 count[node->val]++;
4904 if(node->left != nullptr) {
4905 que.push(node->left);
4906 }
4907 if(node->right != nullptr) {
4908 que.push(node->right);
4909 }
4910 }
4911 bool ans = false;
4912 for(auto it = s.begin(); it != s.end(); ++it) {
4913 int other = k - *it;
4914 if(other == *it) {
4915 if(count[other] > 1) {
4916 ans = true;
4917 break;
4918 }
4919 } else if(s.contains(other)) {
4920 ans = true;
4921 break;
4922 }
4923 }
4924 return ans;
4925 }
4926 }// namespace two_sum_iv_input_is_a_bst
4927
4928 namespace remove_colored_pieces_if_both_neighbors_are_the_same_color {
4929 bool Solution::winnerOfGame(string colors) {
4930 int a_count = 0;
4931 int b_count = 0;
4932 vector vec(colors.length(), true);
4933 vec[0] = false;
4934 vec[colors.length() - 1] = false;
4935 for(int i = 0; i + 1 < colors.length(); i++) {
4936 if(colors[i] != colors[i + 1]) {
4937 vec[i] = false;
4938 vec[i + 1] = false;
4939 }
4940 }
4941 for(int i = 0; i + 1 < colors.length(); i++) {
4942 if(vec[i]) {
4943 if(colors[i] == 'A') {
4944 a_count++;
4945 } else {
4946 b_count++;
4947 }
4948 }
4949 }
4950 return a_count > b_count;
4951 }
4952 }// namespace remove_colored_pieces_if_both_neighbors_are_the_same_color
4953
4954 namespace k_th_smallest_in_lexicographical_order {
4955 int Solution::findKthNumber(int n, int k) {
4956 int curr = 1;
4957 k--;
4958 while(k > 0) {
4959 const int steps = getSteps(curr, n);
4960 if(steps <= k) {
4961 k -= steps;
4962 curr++;
4963 } else {
4964 curr = curr * 10;
4965 k--;
4966 }
4967 }
4968 return curr;
4969 }
4970
4971 int Solution::getSteps(int curr, long n) {
4972 int steps = 0;
4973 long first = curr;
4974 long last = curr;
4975 while(first <= n) {
4976 steps += min(last, n) - first + 1;
4977 first = first * 10;
4978 last = last * 10 + 9;
4979 }
4980 return steps;
4981 }
4982 }// namespace k_th_smallest_in_lexicographical_order
4983
4984 namespace image_smoother {
4985 vector<vector<int>> Solution::imageSmoother(vector<vector<int>> &img) {
4986 const int m = img.size();
4987 const int n = img[0].size();
4988 auto ans = vector(m, vector<int>(n));
4989 for(int i = 0; i < m; i++) {
4990 for(int j = 0; j < n; j++) {
4991 pair<int, int> cells[9] = {make_pair(i - 1, j - 1), make_pair(i - 1, j), make_pair(i - 1, j + 1),
4992 make_pair(i, j - 1), make_pair(i, j), make_pair(i, j + 1),
4993 make_pair(i + 1, j - 1), make_pair(i + 1, j), make_pair(i + 1, j + 1)};
4994 int sum = 0;
4995 int count = 0;
4996 for(int k = 0; k < 9; k++) {
4997 auto [x, y] = cells[k];
4998 if(0 <= x && x < m && 0 <= y && y < n) {
4999 count++;
5000 sum += img[x][y];
5001 }
5002 }
5003 ans[i][j] = sum / count;
5004 }
5005 }
5006 return ans;
5007 }
5008 }// namespace image_smoother
5009
5010 namespace factorial_trailing_zeroes {
5012 unsigned int pow5 = 5;
5013 unsigned int pow2 = 2;
5014 unsigned int count5 = 0;
5015 unsigned int count2 = 0;
5016 while(n / pow5 != 0) {
5017 count5 += n / pow5;
5018 pow5 *= 5;
5019 }
5020 while(n / pow2 != 0) {
5021 count2 += n / pow2;
5022 pow2 *= 2;
5023 }
5024 return min(count2, count5);
5025 }
5026 }// namespace factorial_trailing_zeroes
5027
5028 namespace baseball_game {
5029 int Solution::calPoints(vector<string> &ops) {
5030 vector<int> stk;
5031 for(const string &op: ops) {
5032 if(op == "+") {
5033 const int score1 = stk.back();
5034 const int score2 = *(stk.rbegin() + 1);
5035 stk.push_back(score1 + score2);
5036 } else if(op == "D") {
5037 stk.push_back(2 * stk.back());
5038 } else if(op == "C") {
5039 stk.pop_back();
5040 } else {
5041 stringstream ss;
5042 ss << op;
5043 int score;
5044 ss >> score;
5045 stk.push_back(score);
5046 }
5047 }
5048 int ans = 0;
5049 for(const auto score: stk) {
5050 ans += score;
5051 }
5052 return ans;
5053 }
5054 }// namespace baseball_game
5055
5056 namespace minimum_deletions_to_make_array_beautiful {
5057 int Solution::minDeletion(vector<int> &nums) {
5058 vector<int> indexes;
5059 for(int i = 0; i + 1 < nums.size(); i++) {
5060 if(nums[i] == nums[i + 1]) {
5061 indexes.push_back(i);
5062 }
5063 }
5064 int ans = 0;
5065 bool even = true;
5066 for(const auto index: indexes) {
5067 if(even && index % 2 == 0 || !even && index % 2 != 0) {
5068 ans++;
5069 even = !even;
5070 }
5071 }
5072 if((nums.size() - ans) % 2 != 0) {
5073 ans++;
5074 }
5075 return ans;
5076 }
5077 }// namespace minimum_deletions_to_make_array_beautiful
5078
5079 namespace find_palindrome_with_fixed_length {
5080 unsigned long long qmi(unsigned long long m, unsigned long long k) {
5081 unsigned long long res = 1;
5082 unsigned long long t = m;
5083 while(k != 0U) {
5084 if((k & 1) != 0U) {
5085 res = res * t;
5086 }
5087 t = t * t;
5088 k >>= 1;
5089 }
5090 return res;
5091 }
5092
5093 vector<long long> Solution::kthPalindrome(vector<int> &queries, int intLength) {
5094 vector<long long> ans;
5095 if(intLength == 1) {
5096 for(auto query: queries) {
5097 if(query < 10) {
5098 ans.push_back(query);
5099 } else {
5100 ans.push_back(-1);
5101 }
5102 }
5103 return ans;
5104 }
5105 if(intLength == 2) {
5106 for(auto query: queries) {
5107 if(query < 10) {
5108 ans.push_back(query * 10 + query);
5109 } else {
5110 ans.push_back(-1);
5111 }
5112 }
5113 return ans;
5114 }
5115 int n = (intLength + 1) / 2;
5116 vector<unsigned long long> q10(n + 1);
5117 for(int i = 1; i <= n; i++) {
5118 q10[i] = qmi(10, n - i);
5119 }
5120 for(auto query: queries) {
5121 vector<unsigned long long> num;
5122 int n1 = query / q10[1] + 1;
5123 if(n1 == 10 && query % q10[1] == 0) {
5124 stringstream ss;
5125 for(int i = 0; i < intLength; i++) {
5126 ss << 9;
5127 }
5128 long long res;
5129 ss >> res;
5130 ans.push_back(res);
5131 continue;
5132 }
5133 if(n1 > 9) {
5134 ans.push_back(-1);
5135 continue;
5136 }
5137 if(n1 < 10 && query % q10[1] == 0) {
5138 n1--;
5139 query = (query - 1) % q10[1] + 1;
5140 } else {
5141 query %= q10[1];
5142 }
5143 num.push_back(n1);
5144 for(int i = 2; i <= n; i++) {
5145 int digit = query / q10[i];
5146 if(i == n) {
5147 digit--;
5148 } else if(query != q10[i] && query % q10[i] == 0) {
5149 digit--;
5150 } else if(query == q10[i]) {
5151 digit = 0;
5152 }
5153 query %= q10[i];
5154 num.push_back((digit + 10) % 10);
5155 }
5156 stringstream ss;
5157 for(int digit: num) {
5158 ss << digit;
5159 }
5160 int i = num.size() - 1;
5161 if(intLength % 2 != 0) {
5162 i--;
5163 }
5164 while(i >= 0) {
5165 ss << num[i];
5166 --i;
5167 }
5168 long long res;
5169 ss >> res;
5170 ans.push_back(res);
5171 }
5172 return ans;
5173 }
5174 }// namespace find_palindrome_with_fixed_length
5175
5176 namespace find_missing_observations {
5177 vector<int> Solution::missingRolls(vector<int> &rolls, int mean, int n) {
5178 const int m = rolls.size();
5179 int sum = (m + n) * mean;
5180 for(const auto roll: rolls) {
5181 sum -= roll;
5182 }
5183 if(sum < n || sum > 6 * n) {
5184 return {};
5185 }
5186 vector ans(n, sum / n);
5187 sum %= n;
5188 for(int i = 0; i < sum; i++) {
5189 ans[i]++;
5190 }
5191 return ans;
5192 }
5193 }// namespace find_missing_observations
5194
5195 namespace binary_number_with_alternating_bits {
5197 stringstream ss;
5198 while(n != 0) {
5199 ss << n % 2;
5200 n /= 2;
5201 }
5202 string str;
5203 ss >> str;
5204 for(int i = 0; i + 1 < str.length(); i++) {
5205 if(str[i] == str[i + 1]) {
5206 return false;
5207 }
5208 }
5209 return true;
5210 }
5211 }// namespace binary_number_with_alternating_bits
5212
5213 namespace maximize_the_confusion_of_an_exam {
5214 int Solution::maxConsecutiveAnswers(string answerKey, int k) {
5215 if(answerKey.length() == 1) {
5216 return 1;
5217 }
5218 vector<int> t_count(answerKey.length());
5219 vector<int> f_count(answerKey.length());
5220 int t_current = 0;
5221 int f_current = 0;
5222 for(int i = 0; i < t_count.size(); i++) {
5223 if(answerKey[i] == 'T') {
5224 t_current++;
5225 } else {
5226 f_current++;
5227 }
5228 t_count[i] = t_current;
5229 f_count[i] = f_current;
5230 }
5231 int l = 1;
5232 int r = answerKey.size();
5233 auto check = [&answerKey, &t_count, &f_count, &k](int len) -> bool {
5234 for(int i = 0; i + len <= answerKey.length(); i++) {
5235 int tc = t_count[i + len - 1] - (i - 1 >= 0 ? t_count[i - 1] : 0);
5236 int fc = f_count[i + len - 1] - (i - 1 >= 0 ? f_count[i - 1] : 0);
5237 if(min(tc, fc) <= k) {
5238 return true;
5239 }
5240 }
5241 return false;
5242 };
5243 while(l < r) {
5244 if(l + 1 == r) {
5245 if(check(r)) {
5246 return r;
5247 }
5248 return l;
5249 }
5250 const int mid = (l + r) / 2;
5251 if(check(mid)) {
5252 l = mid;
5253 } else {
5254 r = mid;
5255 }
5256 }
5257 return -1;
5258 }
5259 }// namespace maximize_the_confusion_of_an_exam
5260
5261 namespace find_servers_that_handled_most_number_of_requests {
5262 vector<int> Solution::busiestServers(int k, vector<int> &arrival, vector<int> &load) {
5263 vector<int> ans;
5264 vector count(k, 0);
5265 set<int> available;
5266 for(int i = 0; i < k; i++) {
5267 available.insert(i);
5268 }
5269 priority_queue<event> events;
5270 for(int i = 0; i < arrival.size(); i++) {
5271 event e = {arrival[i], true, i};
5272 events.push(e);
5273 }
5274 while(!events.empty()) {
5275 event e = events.top();
5276 events.pop();
5277 if(e.start) {
5278 if(!available.empty()) {
5279 auto it = available.lower_bound(e.index % k);
5280 if(it == available.end()) {
5281 it = available.begin();
5282 }
5283 event next = {e.time + load[e.index], false, e.index, *it};
5284 events.push(next);
5285 available.erase(it);
5286 }
5287 } else {
5288 //end
5289 available.insert(e.server_index);
5290 count[e.server_index]++;
5291 }
5292 }
5293 const int maximum = *max_element(count.begin(), count.end());
5294 for(int i = 0; i < k; i++) {
5295 if(count[i] == maximum) {
5296 ans.push_back(i);
5297 }
5298 }
5299 return ans;
5300 }
5301
5302 bool event::operator<(const event &e) const {
5303 if(this->time != e.time) {
5304 return this->time > e.time;
5305 }
5306 return this->start;
5307 }
5308 }// namespace find_servers_that_handled_most_number_of_requests
5309
5310 namespace self_dividing_numbers {
5312 vector<int> ans;
5313 for(int i = left; i <= right; ++i) {
5314 stringstream ss;
5315 ss << i;
5316 char ch;
5317 bool flag = true;
5318 while(ss >> ch) {
5319 const int num = ch - '0';
5320 if(num == 0) {
5321 flag = false;
5322 break;
5323 }
5324 if(i % num != 0) {
5325 flag = false;
5326 break;
5327 }
5328 }
5329 if(flag) {
5330 ans.push_back(i);
5331 }
5332 }
5333 return ans;
5334 }
5335 }// namespace self_dividing_numbers
5336
5337 namespace array_of_doubled_pairs {
5338 bool Solution::canReorderDoubled(vector<int> &arr) {
5339 multiset<int> positive;
5340 multiset<int, greater<>> negative;
5341 for(auto num: arr) {
5342 if(num >= 0) {
5343 positive.insert(num);
5344 } else {
5345 negative.insert(num);
5346 }
5347 }
5348 while(!positive.empty()) {
5349 const int num = *positive.begin();
5350 positive.erase(positive.begin());
5351 auto it = positive.find(num * 2);
5352 if(it == positive.end()) {
5353 return false;
5354 }
5355 positive.erase(it);
5356 }
5357 while(!negative.empty()) {
5358 const int num = *negative.begin();
5359 negative.erase(negative.begin());
5360 auto it = negative.find(num * 2);
5361 if(it == negative.end()) {
5362 return false;
5363 }
5364 negative.erase(it);
5365
5366 negative.erase(it);
5367 }
5368 return true;
5369 }
5370 }// namespace array_of_doubled_pairs
5371
5372 namespace strong_password_checker {
5373 int Solution::strongPasswordChecker(const string &password) {
5374 const int n = password.length();
5375 bool has_lower = false;
5376 bool has_upper = false;
5377 bool has_digit = false;
5378 for(const char ch: password) {
5379 if(islower(ch) != 0) {
5380 has_lower = true;
5381 } else if(isupper(ch) != 0) {
5382 has_upper = true;
5383 } else if(isdigit(ch) != 0) {
5384 has_digit = true;
5385 }
5386 }
5387 const int categories = static_cast<int>(has_lower) + static_cast<int>(has_upper) + static_cast<int>(has_digit);
5388
5389 if(n < 6) {
5390 return max(6 - n, 3 - categories);
5391 }
5392 if(n <= 20) {
5393 int replace = 0;
5394 int count = 0;
5395 char current = '#';
5396
5397 for(const char ch: password) {
5398 if(ch == current) {
5399 ++count;
5400 } else {
5401 replace += count / 3;
5402 count = 1;
5403 current = ch;
5404 }
5405 }
5406 replace += count / 3;
5407 return max(replace, 3 - categories);
5408 }
5409 // 替换次数和删除次数
5410 int replace = 0;
5411 int remove = n - 20;
5412 // k mod 3 = 1 的组数,即删除 2 个字符可以减少 1 次替换操作
5413 int rm2 = 0;
5414 int count = 0;
5415 char cur = '#';
5416
5417 for(const char ch: password) {
5418 if(ch == cur) {
5419 ++count;
5420 } else {
5421 if(remove > 0 && count >= 3) {
5422 if(count % 3 == 0) {
5423 // 如果是 k % 3 = 0 的组,那么优先删除 1 个字符,减少 1 次替换操作
5424 --remove;
5425 --replace;
5426 } else if(count % 3 == 1) {
5427 // 如果是 k % 3 = 1 的组,那么存下来备用
5428 ++rm2;
5429 }
5430 // k % 3 = 2 的组无需显式考虑
5431 }
5432 replace += count / 3;
5433 count = 1;
5434 cur = ch;
5435 }
5436 }
5437 if(remove > 0 && count >= 3) {
5438 if(count % 3 == 0) {
5439 --remove;
5440 --replace;
5441 } else if(count % 3 == 1) {
5442 ++rm2;
5443 }
5444 }
5445 replace += count / 3;
5446
5447 // 使用 k % 3 = 1 的组的数量,由剩余的替换次数、组数和剩余的删除次数共同决定
5448 const int use2 = min({replace, rm2, remove / 2});
5449 replace -= use2;
5450 remove -= use2 * 2;
5451 // 由于每有一次替换次数就一定有 3 个连续相同的字符(k / 3 决定),因此这里可以直接计算出使用 k % 3 = 2 的组的数量
5452 const int use3 = min(replace, remove / 3);
5453 replace -= use3;
5454 remove -= use3 * 3;
5455 return n - 20 + max(replace, 3 - categories);
5456 }
5457 }// namespace strong_password_checker
5458
5459 namespace number_of_ways_to_select_buildings {
5460 long long Solution::numberOfWays(string s) {
5461 const unsigned int n = s.length();
5462 vector<unsigned int> prev0(n, 0);
5463 vector<unsigned int> prev1(n, 0);
5464 vector<unsigned int> post0(n, 0);
5465 vector<unsigned int> post1(n, 0);
5466 unsigned current0 = 0;
5467 unsigned current1 = 0;
5468 for(int i = 0; i < n; i++) {
5469 prev0[i] = current0;
5470 prev1[i] = current1;
5471 if(s[i] == '0') {
5472 current0++;
5473 } else {
5474 current1++;
5475 }
5476 }
5477 current0 = 0;
5478 current1 = 0;
5479 for(int i = n - 1; i >= 0; i--) {
5480 post0[i] = current0;
5481 post1[i] = current1;
5482 if(s[i] == '0') {
5483 current0++;
5484 } else {
5485 current1++;
5486 }
5487 }
5488 long long ans = 0;
5489 for(unsigned i = 0; i < n; i++) {
5490 if(s[i] == '0') {
5491 ans += static_cast<long long>(prev1[i]) * post1[i];
5492 } else {
5493 ans += static_cast<long long>(prev0[i]) * post0[i];
5494 }
5495 }
5496 return ans;
5497 }
5498 }// namespace number_of_ways_to_select_buildings
5499
5500 namespace sum_of_scores_of_built_strings {
5501 long long Solution::sumScores(string s) {
5502 const int n = s.length();
5503 long long ans = n;
5504 int l = 0;
5505 int r = 0;
5506 vector z(n, 0);
5507 for(int i = 1; i < n; ++i) {
5508 if(i <= r && z[i - l] < r - i + 1) {
5509 z[i] = z[i - l];
5510 } else {
5511 z[i] = max(0, r - i + 1);
5512 while(i + z[i] < n && s[z[i]] == s[i + z[i]]) {
5513 ++z[i];
5514 }
5515 }
5516 if(i + z[i] - 1 > r) {
5517 l = i;
5518 r = i + z[i] - 1;
5519 }
5520 ans += z[i];
5521 }
5522 return ans;
5523 }
5524 }// namespace sum_of_scores_of_built_strings
5525
5529 namespace minimum_number_of_operations_to_convert_time {
5530 int Solution::convertTime(string current, string correct) {
5531 const int current_h = (current[0] - '0') * 10 + (current[1] - '0');
5532 const int current_m = (current[3] - '0') * 10 + (current[4] - '0');
5533 const int correct_h = (correct[0] - '0') * 10 + (correct[1] - '0');
5534 const int correct_m = (correct[3] - '0') * 10 + (correct[4] - '0');
5535 int diff = correct_h * 60 + correct_m - (current_h * 60 + current_m);
5536 if(diff < 0) {
5537 diff += 24 * 60;
5538 }
5539 int ans = 0;
5540 ans += diff / 60;
5541 diff %= 60;
5542 ans += diff / 15;
5543 diff %= 15;
5544 ans += diff / 5;
5545 diff %= 5;
5546 ans += diff;
5547 return ans;
5548 }
5549 }// namespace minimum_number_of_operations_to_convert_time
5550
5554 namespace find_players_with_zero_or_one_losses {
5555 vector<vector<int>> Solution::findWinners(vector<vector<int>> &matches) {
5556 map<unsigned, unsigned> lose;
5557 for(auto match: matches) {
5558 lose[match[0]] += 0;
5559 lose[match[1]] += 1;
5560 }
5561 vector<vector<int>> ans(2);
5562 vector<int> ans1;
5563 vector<int> ans2;
5564 for(auto [player, count]: lose) {
5565 if(count == 0) {
5566 ans1.push_back(player);
5567 } else if(count == 1) {
5568 ans2.push_back(player);
5569 }
5570 }
5571 ans[0] = ans1;
5572 ans[1] = ans2;
5573 return ans;
5574 }
5575 }// namespace find_players_with_zero_or_one_losses
5576
5580 namespace maximum_candies_allocated_to_k_children {
5581 int Solution::maximumCandies(vector<int> &candies, long long k) {
5582 sort(candies.begin(), candies.end());
5583 long long sum = 0;
5584 for(const auto candy: candies) {
5585 sum += candy;
5586 }
5587 int l = 1;
5588 int r = sum / k;
5589 if(sum < k) {
5590 return 0;
5591 }
5592 while(l < r) {
5593 if(l + 1 == r) {
5594 unsigned long long count = 0;
5595 for(auto it = candies.rbegin(); it != candies.rend() && *it >= r; ++it) {
5596 count += *it / r;
5597 if(count > k) {
5598 break;
5599 }
5600 }
5601 if(count > k) {
5602 return r;
5603 }
5604 return l;
5605 }
5606 const int m = (l + r) / 2;
5607 unsigned long long count = 0;
5608 for(auto it = candies.rbegin(); it != candies.rend() && *it >= m; ++it) {
5609 count += *it / m;
5610 if(count > k) {
5611 break;
5612 }
5613 }
5614 if(count >= k) {
5615 l = m;
5616 } else if(count < k) {
5617 r = m;
5618 }
5619 }
5620 return (l + r) / 2;
5621 }
5622 }// namespace maximum_candies_allocated_to_k_children
5623
5624 namespace encrypt_and_decrypt_strings {
5625 Encrypter::Encrypter(vector<char> &keys, vector<string> &values, vector<string> &dictionary) {
5626 for(int i = 0; i < keys.size(); ++i) {
5627 mp[keys[i] - 'a'] = values[i];
5628 }
5629 for(const auto &s: dictionary) {
5630 ++count[encrypt(s)];
5631 }
5632 }
5633
5634 string Encrypter::encrypt(const string &word1) const {
5635 string res;
5636 for(const char ch: word1) {
5637 const auto &s = mp[ch - 'a'];
5638 if(s.empty()) {
5639 return "";
5640 }
5641 res += s;
5642 }
5643 return res;
5644 }
5645
5646 int Encrypter::decrypt(const string &word2) {
5647 if(count.contains(word2)) {
5648 count[word2] += 0;
5649 return count[word2];
5650 }
5651 // 防止把不在 cnt 中的字符串加进去
5652 return 0;
5653 }
5654 }// namespace encrypt_and_decrypt_strings
5655
5656 namespace range_sum_query_mutable {
5657 NumArray::NumArray(vector<int> &nums)
5658 : nums(nums) {
5659 const int n = nums.size();
5660 size = sqrt(n);
5661 sum.resize((n + size - 1) / size);// n/size 向上取整
5662 for(int i = 0; i < n; i++) {
5663 sum[i / size] += nums[i];
5664 }
5665 }
5666
5667 void NumArray::update(int index, int val) {
5668 sum[index / size] += val - nums[index];
5669 nums[index] = val;
5670 }
5671
5672 int NumArray::sumRange(int left, int right) const {
5673 const int b1 = left / size;
5674 const int i1 = left % size;
5675 const int b2 = right / size;
5676 const int i2 = right % size;
5677 if(b1 == b2) {
5678 // 区间 [left, right] 在同一块中
5679 return accumulate(nums.begin() + b1 * size + i1, nums.begin() + b1 * size + i2 + 1, 0);
5680 }
5681 const int sum1 = accumulate(nums.begin() + b1 * size + i1, nums.begin() + b1 * size + size, 0);
5682 const int sum2 = accumulate(nums.begin() + b2 * size, nums.begin() + b2 * size + i2 + 1, 0);
5683 const int sum3 = accumulate(sum.begin() + b1 + 1, sum.begin() + b2, 0);
5684 return sum1 + sum2 + sum3;
5685 }
5686 }// namespace range_sum_query_mutable
5687
5688 namespace process_restricted_friend_requests {
5689 vector<bool> Solution::friendRequests(int n, vector<vector<int>> &restrictions, vector<vector<int>> &requests) {
5690 UnionFind uf(n);
5691 vector<bool> ans(requests.size());
5692 auto check = [&uf, &restrictions](int x, int y) -> bool {
5693 x = uf.find(x);
5694 y = uf.find(y);
5695 if(x > y) {
5696 swap(x, y);
5697 }
5698 for(auto &restriction: restrictions) {
5699 int i = uf.find(restriction[0]);
5700 int j = uf.find(restriction[1]);
5701 if(i > j) {
5702 swap(i, j);
5703 }
5704 if(i == x && j == y) {
5705 return false;
5706 }
5707 }
5708 return true;
5709 };
5710 for(int i = 0; i < requests.size(); i++) {
5711 if(check(requests[i][0], requests[i][1])) {
5712 uf.unite(requests[i][0], requests[i][1]);
5713 ans[i] = true;
5714 } else {
5715 ans[i] = false;
5716 }
5717 }
5718 return ans;
5719 }
5720 }// namespace process_restricted_friend_requests
5721
5722 namespace prime_number_of_set_bits_in_binary_representation {
5724 int ans = 0;
5725 const unordered_set primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61};
5726 for(unsigned i = left; i <= right; i++) {
5727 if(primes.contains(popcount(i))) {
5728 ans++;
5729 }
5730 }
5731 return ans;
5732 }
5733 }// namespace prime_number_of_set_bits_in_binary_representation
5734
5735 namespace minimum_height_trees {
5736 vector<int> Solution::findMinHeightTrees(int n, vector<vector<int>> &edges) {
5737 if(n == 1) {
5738 return {0};
5739 }
5740 vector<vector<int>> adj(n);
5741 for(auto &edge: edges) {
5742 adj[edge[0]].emplace_back(edge[1]);
5743 adj[edge[1]].emplace_back(edge[0]);
5744 }
5745
5746 vector parent(n, -1);
5747 /* 找到与节点 0 最远的节点 x */
5748 const int x = findLongestNode(0, parent, adj);
5749 /* 找到与节点 x 最远的节点 y */
5750 int y = findLongestNode(x, parent, adj);
5751 /* 求出节点 x 到节点 y 的路径 */
5752 vector<int> path;
5753 parent[x] = -1;
5754 while(y != -1) {
5755 path.emplace_back(y);
5756 y = parent[y];
5757 }
5758 const int m = path.size();
5759 if(m % 2 == 0) {
5760 return {path[m / 2 - 1], path[m / 2]};
5761 }
5762 return {path[m / 2]};
5763 }
5764
5765 int Solution::findLongestNode(int u, vector<int> &parent, vector<vector<int>> &adj) {
5766 const int n = adj.size();
5767 queue<int> qu;
5768 vector<bool> visit(n);
5769 qu.emplace(u);
5770 visit[u] = true;
5771 int node = -1;
5772
5773 while(!qu.empty()) {
5774 const int curr = qu.front();
5775 qu.pop();
5776 node = curr;
5777 for(auto &v: adj[curr]) {
5778 if(!visit[v]) {
5779 visit[v] = true;
5780 parent[v] = curr;
5781 qu.emplace(v);
5782 }
5783 }
5784 }
5785 return node;
5786 }
5787 }// namespace minimum_height_trees
5788
5789 namespace rotate_string {
5790 bool Solution::rotateString(string s, const string &goal) {
5791 if(s.length() != goal.length()) {
5792 return false;
5793 }
5794 s += s;
5795 return s.find(goal) != string::npos;
5796 }
5797 }// namespace rotate_string
5798
5799 namespace n_ary_tree_level_order_traversal {
5800 vector<vector<int>> Solution::levelOrder(Node *root) {
5801 queue<pair<int, Node *>> q;
5802 vector<vector<int>> ans;
5803 if(root == nullptr) {
5804 return ans;
5805 }
5806 q.push(make_pair(0, root));
5807 while(!q.empty()) {
5808 auto [level, node] = q.front();
5809 if(ans.size() == level) {
5810 ans.emplace_back();
5811 }
5812 ans[level].push_back(node->val);
5813 q.pop();
5814 for(auto *next: node->children) {
5815 q.push(make_pair(level + 1, next));
5816 }
5817 }
5818 return ans;
5819 }
5820 }// namespace n_ary_tree_level_order_traversal
5821
5822 namespace reaching_points {
5823 bool Solution::reachingPoints(int sx, int sy, int tx, int ty) {
5824 while(tx > sx && ty > sy && tx != ty) {
5825 if(tx > ty) {
5826 tx %= ty;
5827 } else {
5828 ty %= tx;
5829 }
5830 }
5831 if(tx == sx && ty == sy) {
5832 return true;
5833 }
5834 if(tx == sx) {
5835 return ty > sy && (ty - sy) % tx == 0;
5836 }
5837 if(ty == sy) {
5838 return tx > sx && (tx - sx) % ty == 0;
5839 }
5840 return false;
5841 }
5842 }// namespace reaching_points
5843
5844 namespace maximum_product_after_k_increments {
5845 int Solution::maximumProduct(vector<int> &nums, int k) {
5846 priority_queue<int, vector<int>, greater<int>> pq;
5847 for(auto num: nums) {
5848 pq.push(num);
5849 }
5850 while(k-- != 0) {
5851 const int num = pq.top();
5852 pq.pop();
5853 pq.push(num + 1);
5854 }
5855 long long ans = 1;
5856 while(!pq.empty()) {
5857 const int num = pq.top();
5858 pq.pop();
5859 ans *= num;
5860 ans %= 1000000007;
5861 }
5862 return ans;
5863 }
5864 }// namespace maximum_product_after_k_increments
5865
5866 namespace maximum_total_beauty_of_the_gardens {
5867 long long Solution::maximumBeauty(vector<int> &flowers, long long newFlowers, int target, int full, int partial) {
5868 const int n = flowers.size();
5869 sort(flowers.begin(), flowers.end());
5870 for(int i = 0; i < n; i++) {
5871 flowers[i] = min(flowers[i], target);
5872 }
5873 long long ans = 0;
5874 vector<long long> sum(n + 1, 0);
5875 for(int i = 0; i < n; i++) {
5876 sum[i + 1] = sum[i] + flowers[i];
5877 }
5878 for(int i = 0, j = 0; i <= n; i++) {
5879 const long long rest = newFlowers - (static_cast<long long>(target) * (n - i) - (sum[n] - sum[i]));
5880 if(rest >= 0) {
5881 while(j < i && rest >= static_cast<long long>(flowers[j]) * j - sum[j]) {
5882 //将前j项补齐到flowers[j]
5883 j++;
5884 }
5885 ans = max(ans, static_cast<long long>(full) * (n - i) + (j == 0 ? 0 : static_cast<long long>(partial) * min(static_cast<long long>(target - 1), (rest + sum[j]) / j)));
5886 }
5887 if(i < n && flowers[i] == target) {
5888 break;
5889 }
5890 }
5891 return ans;
5892 }
5893 }// namespace maximum_total_beauty_of_the_gardens
5894
5895 namespace count_numbers_with_unique_digits {
5897 if(n == 0) {
5898 return 1;
5899 }
5900 vector<int> dp(n + 1);
5901 dp[1] = 9;
5902 for(int i = 2; i <= n; ++i) {
5903 dp[i] = dp[i - 1] * (10 - (i - 1));
5904 }
5905 int ans = 0;
5906 for(int i = 1; i <= n; ++i) {
5907 ans += dp[i];
5908 }
5909 return ans + 1;
5910 }
5911 }// namespace count_numbers_with_unique_digits
5912
5913 namespace number_of_lines_to_write_string {
5914 vector<int> Solution::numberOfLines(vector<int> &widths, string s) {
5915 int lines = 1;
5916 int current = 0;
5917 for(int i = 0; i < s.length(); i++) {
5918 if(current + widths[s[i] - 'a'] > 100) {
5919 current = 0;
5920 lines++;
5921 }
5922 current += widths[s[i] - 'a'];
5923 }
5924 return {lines, current};
5925 }
5926 }// namespace number_of_lines_to_write_string
5927
5928 namespace permutation_in_string {
5929 bool Solution::checkInclusion(const string &s1, string s2) {
5930 if(s1.length() > s2.length()) {
5931 return false;
5932 }
5933 unordered_map<char, int> um1;
5934 unordered_map<char, int> um2;
5935 for(char ch: s1) {
5936 um1[ch]++;
5937 }
5938 for(int i = 0; i < s1.length(); i++) {
5939 um2[s2[i]]++;
5940 }
5941 if(um2 == um1) {
5942 return true;
5943 }
5944 for(int i = 0; i + s1.length() < s2.length(); i++) {
5945 um2[s2[i]]--;
5946 um2[s2[i + s1.length()]]++;
5947 if(um2[s2[i]] == 0) {
5948 um2.erase(s2[i]);
5949 }
5950 if(um2 == um1) {
5951 return true;
5952 }
5953 }
5954 return false;
5955 }
5956 }// namespace permutation_in_string
5957
5958 namespace insert_delete_getrandom_o1 {
5960 generator = default_random_engine(time(nullptr));
5961 distribution = uniform_int_distribution(0, INT_MAX);
5962 }
5963
5965 if(static_cast<unsigned int>(map.contains(val)) != 0U) {
5966 return false;
5967 }
5968 nums.push_back(val);
5969 map[val] = nums.size() - 1;
5970 return true;
5971 }
5972
5974 if(static_cast<unsigned int>(map.contains(val)) == 0U) {
5975 return false;
5976 }
5977 const int index = map[val];
5978 const int last = nums.back();
5979 nums[index] = last;
5980 map[last] = index;
5981 nums.pop_back();
5982 map.erase(val);
5983 return true;
5984 }
5985
5987 }// namespace insert_delete_getrandom_o1
5988
5989 namespace projection_area_of_3d_shapes {
5990 int Solution::projectionArea(vector<vector<int>> &grid) {
5991 const int n = grid.size();
5992 int xy = 0;
5993 int xz = 0;
5994 int yz = 0;
5995 auto grid_xz = vector(51, vector(51, 0));
5996 auto grid_yz = vector(51, vector(51, 0));
5997 for(int i = 0; i < n; i++) {
5998 for(int j = 0; j < n; j++) {
5999 if(grid[i][j] != 0) {
6000 xy++;
6001 }
6002 for(int k = 0; k < grid[i][j]; k++) {
6003 grid_xz[i][k] = 1;
6004 grid_yz[j][k] = 1;
6005 }
6006 }
6007 }
6008 for(int i = 0; i < 51; i++) {
6009 for(int j = 0; j < 51; j++) {
6010 if(grid_xz[i][j] != 0) {
6011 xz++;
6012 }
6013 if(grid_yz[i][j] != 0) {
6014 yz++;
6015 }
6016 }
6017 }
6018 return xy + yz + xz;
6019 }
6020 }// namespace projection_area_of_3d_shapes
6021
6022 namespace design_parking_system {
6023 ParkingSystem::ParkingSystem(int big, int medium, int small)
6024 : big(big), medium(medium), small(small) {}
6025
6026 bool ParkingSystem::addCar(int carType) {
6027 switch(carType) {
6028 case 1: {
6029 if(big > 0) {
6030 big--;
6031 return true;
6032 }
6033 return false;
6034 }
6035 case 2: {
6036 if(medium > 0) {
6037 medium--;
6038 return true;
6039 }
6040 return false;
6041 }
6042 case 3: {
6043 if(small > 0) {
6044 small--;
6045 return true;
6046 }
6047 return false;
6048 }
6049 default: return false;
6050 }
6051 }
6052 }// namespace design_parking_system
6053
6054 namespace range_sum_query_immutable {
6055 NumArray::NumArray(vector<int> &nums) {
6056 pref_sum = vector<int>(nums.size());
6057 pref_sum[0] = nums[0];
6058 for(int i = 1; i < nums.size(); i++) {
6059 pref_sum[i] = pref_sum[i - 1] + nums[i];
6060 }
6061 }
6062
6063 int NumArray::sumRange(int left, int right) const { return pref_sum[right] - (left - 1 >= 0 ? pref_sum[left - 1] : 0); }
6064 }// namespace range_sum_query_immutable
6065
6066 namespace house_robber {
6067 int Solution::rob(vector<int> &nums) {
6068 if(nums.size() == 1) {
6069 return nums[0];
6070 }
6071 vector<int> dp(nums.size());
6072 dp[0] = nums[0];
6073 dp[1] = max(nums[0], nums[1]);
6074 for(int i = 2; i < nums.size(); i++) {
6075 dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
6076 }
6077 return dp[nums.size() - 1];
6078 }
6079 }// namespace house_robber
6080
6081 namespace triangle {
6082 int Solution::minimumTotal(vector<vector<int>> &triangle) {
6083 vector<vector<int>> dp = triangle;
6084 for(int i = 1; i < triangle.size(); i++) {
6085 for(int j = 0; j < triangle[i].size(); j++) {
6086 if(j == 0) {
6087 dp[i][j] = dp[i - 1][j] + triangle[i][j];
6088 } else if(j == triangle[i].size() - 1) {
6089 dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];
6090 } else {
6091 dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j];
6092 }
6093 }
6094 }
6095 int ans = dp.back()[0];
6096 for(int i = 0; i < dp.back().size(); i++) {
6097 ans = min(ans, dp.back()[i]);
6098 }
6099 return ans;
6100 }
6101 }// namespace triangle
6102
6103 namespace lowest_common_ancestor_of_a_binary_search_tree {
6105 auto *const tnp = new TreeNodeP(root->val);
6106 TreeNodeP *pp;
6107 TreeNodeP *qq;
6108 copy(root, tnp, p->val, q->val, &pp, &qq);
6109 TreeNodeP *current = pp;
6110 while(current != nullptr) {
6111 current->ed = true;
6112 current = current->parent;
6113 }
6114 current = qq;
6115 while(current != nullptr) {
6116 if(current->ed) {
6117 return current->mirror;
6118 }
6119 current = current->parent;
6120 }
6121 return root;
6122 }
6123
6124 void Solution::copy(TreeNode *tn, TreeNodeP *tnp, int low, int high, TreeNodeP **p, TreeNodeP **q) {
6125 tnp->mirror = tn;
6126 if(tn->val == low) {
6127 *p = tnp;
6128 } else if(tn->val == high) {
6129 *q = tnp;
6130 }
6131 if(tn->left != nullptr) {
6132 tnp->left = new TreeNodeP(tn->left->val);
6133 tnp->left->parent = tnp;
6134 copy(tn->left, tnp->left, low, high, p, q);
6135 }
6136 if(tn->right != nullptr) {
6137 tnp->right = new TreeNodeP(tn->right->val);
6138 tnp->right->parent = tnp;
6139 copy(tn->right, tnp->right, low, high, p, q);
6140 }
6141 }
6142 }// namespace lowest_common_ancestor_of_a_binary_search_tree
6143
6144 namespace shuffle_an_array {
6145 vector<int> Solution::reset() { return nums; }
6146
6147 vector<int> Solution::shuffle() const {
6148 vector<int> ans;
6149 vector<int> cpy = nums;
6150 while(!cpy.empty()) {
6151 const int idx = rand() % cpy.size();
6152 ans.emplace_back(cpy[idx]);
6153 cpy.erase(cpy.begin() + idx);
6154 }
6155 return ans;
6156 }
6157
6158 Solution::Solution(vector<int> &nums)
6159 : nums(nums) { srand(time(nullptr)); }
6160 }// namespace shuffle_an_array
6161
6162 namespace find_all_anagrams_in_a_string {
6163 vector<int> Solution::findAnagrams(string s, const string &p) {
6164 vector<int> ans;
6165 unordered_map<char, int> um_p;
6166 for(char ch: p) {
6167 um_p[ch]++;
6168 }
6169 unordered_map<char, int> um_s;
6170 for(int i = 0; i < p.length(); i++) {
6171 um_s[s[i]]++;
6172 }
6173 if(um_s == um_p) {
6174 ans.emplace_back(0);
6175 }
6176 for(int i = p.length(); i < s.length(); i++) {
6177 um_s[s[i]]++;
6178 um_s[s[i - p.length()]]--;
6179 if(um_s[s[i - p.length()]] == 0) {
6180 um_s.erase(s[i - p.length()]);
6181 }
6182 if(um_s == um_p) {
6183 ans.emplace_back(i - p.length() + 1);
6184 }
6185 }
6186 return ans;
6187 }
6188 }// namespace find_all_anagrams_in_a_string
6189
6190 namespace subarray_product_less_than_k {
6191 int Solution::numSubarrayProductLessThanK(vector<int> &nums, int k) {
6192 int ans = 0;
6193 int prod = 1;
6194 int i = 0;
6195 for(int j = 0; j < nums.size(); j++) {
6196 prod *= nums[j];
6197 while(i <= j && prod >= k) {
6198 prod /= nums[i];
6199 i++;
6200 }
6201 ans += j - i + 1;
6202 }
6203 return ans;
6204 }
6205 }// namespace subarray_product_less_than_k
6206
6207 namespace minimum_size_subarray_sum {
6208 int Solution::minSubArrayLen(int target, vector<int> &nums) {
6209 int r = nums.size() - 1;
6210 int l = r;
6211 int sum = nums[r];
6212 int ans = 0;
6213 while(l >= 0 && l <= r) {
6214 if(nums[l] >= target) {
6215 return 1;
6216 }
6217 while(l - 1 >= 0 && sum + nums[l - 1] < target) {
6218 sum += nums[--l];
6219 }
6220 if(l - 1 >= 0) {
6221 l--;
6222 sum += nums[l];
6223 if(ans == 0) {
6224 ans = r - l + 1;
6225 } else {
6226 ans = min(ans, r - l + 1);
6227 }
6228 } else {
6229 break;
6230 }
6231 do {
6232 sum -= nums[r--];
6233 if(sum >= target) {
6234 ans = min(ans, r - l + 1);
6235 }
6236 } while(sum >= target && r >= l);
6237 }
6238 return ans;
6239 }
6240 }// namespace minimum_size_subarray_sum
6241
6242 namespace populating_next_right_pointers_in_each_node_ii {
6244 if(root == nullptr) {
6245 return nullptr;
6246 }
6247 int prev_level = 0;
6248 Node *prev_node = root;
6249 queue<pair<int, Node *>> q;
6250 if(root->left != nullptr) {
6251 q.emplace(1, root->left);
6252 }
6253 if(root->right != nullptr) {
6254 q.emplace(1, root->right);
6255 }
6256 while(!q.empty()) {
6257 auto [level, node] = q.front();
6258 q.pop();
6259 if(level == prev_level) {
6260 prev_node->next = node;
6261 }
6262 prev_level = level;
6263 prev_node = node;
6264 if(node->left != nullptr) {
6265 q.emplace(level + 1, node->left);
6266 }
6267 if(node->right != nullptr) {
6268 q.emplace(level + 1, node->right);
6269 }
6270 }
6271 return root;
6272 }
6273 }// namespace populating_next_right_pointers_in_each_node_ii
6274
6275 namespace subtree_of_another_tree {
6277 if(root == nullptr) {
6278 return false;
6279 }
6280 queue<TreeNode *> q;
6281 q.push(root);
6282 while(!q.empty()) {
6283 auto *const node = q.front();
6284 q.pop();
6285 if(equal(node, subRoot)) {
6286 return true;
6287 }
6288 if(node->left != nullptr) {
6289 q.push(node->left);
6290 }
6291 if(node->right != nullptr) {
6292 q.push(node->right);
6293 }
6294 }
6295 return false;
6296 }
6297
6299 if(static_cast<int>(tn1 == nullptr) + static_cast<int>(tn2 == nullptr) == 1) {
6300 return false;
6301 }
6302 if(tn1 == nullptr && tn2 == nullptr) {
6303 return true;
6304 }
6305 if(tn1->val != tn2->val) {
6306 return false;
6307 }
6308 if(static_cast<int>(tn1->left == nullptr) + static_cast<int>(tn2->left == nullptr) == 1) {
6309 return false;
6310 }
6311 if(static_cast<int>(tn1->right == nullptr) + static_cast<int>(tn2->right == nullptr) == 1) {
6312 return false;
6313 }
6314 return equal(tn1->left, tn2->left) && equal(tn1->right, tn2->right);
6315 }
6316 }// namespace subtree_of_another_tree
6317
6318 namespace shortest_path_in_binary_matrix {
6319 int Solution::shortestPathBinaryMatrix(vector<vector<int>> &grid) {
6320 int n = grid.size();
6321 auto levels = vector(n, vector(n, -1));
6322 auto cmp = [&n](const tuple<int, int, int> &t1, const tuple<int, int, int> &t2) {
6323 const auto &[level1, x1, y1] = t1;
6324 const auto &[level2, x2, y2] = t2;
6325 const int dx1 = abs(n - 1 - x1);
6326 const int dy1 = abs(n - 1 - y1);
6327 const int dx2 = abs(n - 1 - x2);
6328 const int dy2 = abs(n - 1 - y2);
6329 return level1 + dx1 + dy1 - min(dx1, dy1) > level2 + dx2 + dy2 - min(dx2, dy2);
6330 };
6331 priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);
6332 if(grid[0][0] == 0 && grid[n - 1][n - 1] == 0) {
6333 pq.push(make_tuple(1, 0, 0));
6334 } else {
6335 return -1;
6336 }
6337 while(!pq.empty()) {
6338 auto [level, x, y] = pq.top();
6339 if(x == n - 1 && y == n - 1) {
6340 return level;
6341 }
6342 pq.pop();
6343 if(levels[x][y] == -1 || levels[x][y] > level) {
6344 levels[x][y] = level;
6345 } else {
6346 continue;
6347 }
6348 pair<int, int> nexts[8] = {make_pair(x - 1, y - 1), make_pair(x - 1, y), make_pair(x - 1, y + 1),
6349 make_pair(x, y - 1), make_pair(x, y + 1),
6350 make_pair(x + 1, y - 1), make_pair(x + 1, y), make_pair(x + 1, y + 1)};
6351 for(auto [next_x, next_y]: nexts) {
6352 if(next_x >= 0 && next_x < n && next_y >= 0 && next_y < n && grid[next_x][next_y] == 0 && (levels[next_x][next_y] == -1 || levels[next_x][next_y] > level + 1)) {
6353 pq.push(make_tuple(level + 1, next_x, next_y));
6354 }
6355 }
6356 }
6357 return -1;
6358 }
6359 }// namespace shortest_path_in_binary_matrix
6360
6361 namespace surrounded_regions {
6362 void Solution::solve(vector<vector<char>> &board) {
6363 const int m = board.size();
6364 const int n = board[0].size();
6365 for(int i = 0; i < n; i++) {
6366 if(board[0][i] == 'O') {
6367 dfs(board, 0, i);
6368 }
6369 if(board[m - 1][i] == 'O') {
6370 dfs(board, m - 1, i);
6371 }
6372 }
6373 for(int j = 0; j < m; j++) {
6374 if(board[j][0] == 'O') {
6375 dfs(board, j, 0);
6376 }
6377 if(board[j][n - 1] == 'O') {
6378 dfs(board, j, n - 1);
6379 }
6380 }
6381 for(int i = 0; i < m; i++) {
6382 for(int j = 0; j < n; j++) {
6383 if(board[i][j] == 'O') {
6384 board[i][j] = 'X';
6385 }
6386 if(board[i][j] == 'D') {
6387 board[i][j] = 'O';
6388 }
6389 }
6390 }
6391 }
6392
6393 void Solution::dfs(vector<vector<char>> &board, int x, int y) {
6394 board[x][y] = 'D';
6395 const int m = board.size();
6396 const int n = board[0].size();
6397 pair<int, int> nexts[4] = {{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}};
6398 for(auto [next_x, next_y]: nexts) {
6399 if(next_x >= 0 && next_x < m && next_y >= 0 && next_y < n && board[next_x][next_y] == 'O') {
6400 dfs(board, next_x, next_y);
6401 }
6402 }
6403 }
6404 }// namespace surrounded_regions
6405
6406 namespace all_paths_from_source_to_target {
6407 vector<vector<int>> Solution::allPathsSourceTarget(vector<vector<int>> &graph) {
6408 vector<vector<int>> ans;
6409 dfs(graph, ans, 0);
6410 for(auto &path: ans) {
6411 path.push_back(0);
6412 path = vector(path.rbegin(), path.rend());
6413 }
6414 return ans;
6415 }
6416
6417 int Solution::dfs(vector<vector<int>> &graph, vector<vector<int>> &ans, int cur) {
6418 int ret = 0;
6419 if(cur == graph.size() - 1) {
6420 ans.emplace_back(vector(1, cur));
6421 return 1;
6422 }
6423 for(const auto next: graph[cur]) {
6424 const int n = dfs(graph, ans, next);
6425 ret += n;
6426 for(int i = ans.size() - 1, j = 0; j < n; i--, j++) {
6427 ans[i].emplace_back(cur);
6428 }
6429 }
6430 return ret;
6431 }
6432 }// namespace all_paths_from_source_to_target
6433
6434 namespace permutations_ii {
6435 vector<vector<int>> Solution::permuteUnique(vector<int> &nums) {
6436 vector<vector<int>> ans;
6437 set<vector<int>> s;
6438 dfs(s, vector<int>(), nums);
6439 ans.reserve(s.size());
6440 for(const auto &vec: s) {
6441 ans.emplace_back(vec);
6442 }
6443 return ans;
6444 }
6445
6446 void Solution::dfs(set<vector<int>> &s, const vector<int> &current, vector<int> rest) {
6447 if(rest.empty()) {
6448 s.insert(current);
6449 return;
6450 }
6451 for(auto it = rest.begin(); it != rest.end(); ++it) {
6452 vector<int> next_current = current;
6453 vector<int> next_rest = rest;
6454 next_current.push_back(*it);
6455 next_rest.erase(next_rest.begin() + (it - rest.begin()));
6456 dfs(s, next_current, next_rest);
6457 }
6458 }
6459 }// namespace permutations_ii
6460
6461 namespace combination_sum {
6462 vector<vector<int>> Solution::combinationSum(vector<int> &candidates, int target) {
6463 sort(candidates.begin(), candidates.end());
6464 return recurse(candidates, target, 0);
6465 }
6466
6467 vector<vector<int>> Solution::recurse(vector<int> &candidates, int target, int index) {
6468 vector<vector<int>> ans;
6469 for(int i = index; i < candidates.size(); i++) {
6470 auto &candidate = candidates[i];
6471 if(candidate == target) {
6472 ans.emplace_back(vector(1, candidate));
6473 } else if(target - candidate >= 1) {
6474 auto res = recurse(candidates, target - candidate, i);
6475 for(auto &vec: res) {
6476 vec.push_back(candidate);
6477 ans.push_back(vec);
6478 }
6479 }
6480 }
6481 return ans;
6482 }
6483 }// namespace combination_sum
6484
6485 namespace combination_sum_ii {
6486 vector<vector<int>> Solution::combinationSum2(vector<int> &candidates, int target) {
6487 sort(candidates.begin(), candidates.end());
6488 const auto ret = recurse(candidates, target, -10);
6489 vector<vector<int>> ans(ret.size());
6490 for(int i = 0; i < ret.size(); i++) {
6491 ans[i] = vector<int>(ret[i].size());
6492 for(int j = 0; j < ret[i].size(); j++) {
6493 ans[i][j] = candidates[ret[i][j]];
6494 }
6495 }
6496 return ans;
6497 }
6498
6499 vector<vector<int>> Solution::recurse(vector<int> &candidates, int target, int index) {
6500 vector<vector<int>> ans;
6501 for(int i = max(0, index + 1); i < candidates.size(); i++) {
6502 if(!(i > 0 && candidates[i] == candidates[i - 1] && index != i - 1)) {
6503 const auto &candidate = candidates[i];
6504 if(candidate == target) {
6505 ans.emplace_back(vector(1, i));
6506 } else if(target - candidate >= 1) {
6507 auto res = recurse(candidates, target - candidate, i);
6508 for(auto &vec: res) {
6509 vec.push_back(i);
6510 ans.push_back(vec);
6511 }
6512 }
6513 }
6514 }
6515 return ans;
6516 }
6517 }// namespace combination_sum_ii
6518
6519 namespace house_robber_ii {
6520 int Solution::rob(vector<int> &nums) {
6521 if(nums.size() == 1) {
6522 return nums[0];
6523 }
6524 auto vec1 = vector(nums.begin(), nums.end() - 1);
6525 auto vec2 = vector(nums.begin() + 1, nums.end());
6527 }
6528 }// namespace house_robber_ii
6529
6530 namespace jump_game {
6531 bool Solution::canJump(vector<int> &nums) {
6532 vector can(nums.size(), false);
6533 can[0] = true;
6534 int last = 0;
6535 for(int i = 0; i < nums.size(); i++) {
6536 if(can[i] && min(i + nums[i], static_cast<int>(nums.size() - 1)) > last) {
6537 for(int j = last + 1; j <= i + nums[i] && j < nums.size(); j++) {
6538 can[j] = true;
6539 }
6540 last = min(i + nums[i], static_cast<int>(nums.size() - 1));
6541 }
6542 }
6543 return can.back();
6544 }
6545 }// namespace jump_game
6546
6547 namespace jump_game_ii {
6548 int Solution::jump(vector<int> &nums) {
6549 const int n = nums.size();
6550 int ans = 0;
6551 int last = n - 1;
6552 while(last != 0) {
6553 for(int i = 0; i < n; i++) {
6554 if(i + nums[i] >= last) {
6555 last = i;
6556 ans++;
6557 break;
6558 }
6559 }
6560 }
6561 return ans;
6562 }
6563 }// namespace jump_game_ii
6564
6565 namespace unique_paths {
6566 int Solution::uniquePaths(int m, int n) {
6567 vector dp(m, vector(n, 0));
6568 dp[m - 1][n - 1] = 1;
6569 for(int i = m - 1; i >= 0; i--) {
6570 for(int j = n - 1; j >= 0; j--) {
6571 if(i + 1 < m) {
6572 dp[i][j] += dp[i + 1][j];
6573 }
6574 if(j + 1 < n) {
6575 dp[i][j] += dp[i][j + 1];
6576 }
6577 }
6578 }
6579 return dp[0][0];
6580 }
6581 }// namespace unique_paths
6582
6583 namespace longest_palindromic_substring {
6585 const int n = s.size();
6586 if(n < 2) {
6587 return s;
6588 }
6589
6590 int maxLen = 1;
6591 int begin = 0;
6592 // dp[i][j] 表示 s[i..j] 是否是回文串
6593 vector dp(n, vector<int>(n));
6594 // 初始化:所有长度为 1 的子串都是回文串
6595 for(int i = 0; i < n; i++) {
6596 dp[i][i] = 1;
6597 }
6598 // 递推开始
6599 // 先枚举子串长度
6600 for(int L = 2; L <= n; L++) {
6601 // 枚举左边界,左边界的上限设置可以宽松一些
6602 for(int i = 0; i < n; i++) {
6603 // 由 L 和 i 可以确定右边界,即 j - i + 1 = L 得
6604 const int j = L + i - 1;
6605 // 如果右边界越界,就可以退出当前循环
6606 if(j >= n) {
6607 break;
6608 }
6609
6610 if(s[i] != s[j]) {
6611 dp[i][j] = 0;
6612 } else {
6613 if(j - i < 3) {
6614 dp[i][j] = 1;
6615 } else {
6616 dp[i][j] = dp[i + 1][j - 1];
6617 }
6618 }
6619
6620 // 只要 dp[i][L] == true 成立,就表示子串 s[i..L] 是回文,此时记录回文长度和起始位置
6621 if(dp[i][j] != 0 && j - i + 1 > maxLen) {
6622 maxLen = j - i + 1;
6623 begin = i;
6624 }
6625 }
6626 }
6627 return s.substr(begin, maxLen);
6628 }
6629 }// namespace longest_palindromic_substring
6630
6631 namespace arithmetic_slices {
6632 int Solution::numberOfArithmeticSlices(vector<int> &nums) {
6633 const int n = nums.size();
6634 vector<int> diff(n - 1);
6635 for(int i = 0; i < n - 1; i++) {
6636 diff[i] = nums[i + 1] - nums[i];
6637 }
6638 vector<int> consecutive;
6639 int prev = 0;
6640 int cnt = 0;
6641 for(int i = 0; i < n - 1; i++) {
6642 if(diff[i] == diff[prev]) {
6643 cnt++;
6644 } else {
6645 consecutive.emplace_back(cnt);
6646 prev = i;
6647 cnt = 1;
6648 }
6649 }
6650 consecutive.emplace_back(cnt);
6651 int ans = 0;
6652 for(const auto num: consecutive) {
6653 if(num >= 2) {
6654 ans += (num - 1) * num / 2;
6655 }
6656 }
6657 return ans;
6658 }
6659 }// namespace arithmetic_slices
6660
6661 namespace decode_ways {
6663 vector dp(s.length(), 0);
6664 for(int i = 0; i < dp.size(); i++) {
6665 bool ok = false;
6666 if('1' <= s[i] && s[i] <= '9') {
6667 dp[i] += i - 1 >= 0 ? dp[i - 1] : 1;
6668 ok = true;
6669 }
6670 if(i - 1 >= 0 && (s[i - 1] == '1' && '0' <= s[i] && s[i] <= '9' || s[i - 1] == '2' && '0' <= s[i] && s[i] <= '6')) {
6671 dp[i] += i - 2 >= 0 ? dp[i - 2] : 1;
6672 ok = true;
6673 }
6674 if(!ok) {
6675 return 0;
6676 }
6677 }
6678 return dp.back();
6679 }
6680 }// namespace decode_ways
6681
6682 namespace word_break {
6683 bool Solution::wordBreak(const string &s, vector<string> &wordDict) {
6684 vector end(s.length(), false);
6685 TrieNode tn(0);
6686 for(const auto &word: wordDict) {
6687 tn.insert(word);
6688 }
6689 search(&tn, s, 0, end);
6690 for(int i = 1; i < s.length(); i++) {
6691 if(end[i - 1]) {
6692 search(&tn, s, i, end);
6693 if(end.back()) {
6694 return true;
6695 }
6696 }
6697 }
6698 return end.back();
6699 }
6700
6701 void Solution::search(const TrieNode *tn, const string &s, int i, vector<bool> &end) {
6702 const TrieNode *node = tn;
6703 for(; i < s.length(); i++) {
6704 node = node->nexts[s[i] - 'a'];
6705 if(node == nullptr) {
6706 return;
6707 }
6708 if(node->end_of_word) {
6709 end[i] = true;
6710 }
6711 }
6712 }
6713 }// namespace word_break
6714
6715 namespace longest_increasing_subsequence {
6716 int Solution::lengthOfLIS(vector<int> &nums) {
6717 const int n = nums.size();
6718 int ans = 1;
6719 vector dp(n, 1);//length of longest increasing subsequence end with i
6720 for(int i = 0; i < n; i++) {
6721 for(int j = i + 1; j < n; j++) {
6722 if(nums[j] > nums[i]) {
6723 dp[j] = max(dp[j], dp[i] + 1);
6724 }
6725 }
6726 ans = max(ans, dp[i]);
6727 }
6728 return ans;
6729 }
6730 }// namespace longest_increasing_subsequence
6731
6732 namespace number_of_longest_increasing_subsequence {
6733 int Solution::findNumberOfLIS(vector<int> &nums) {
6734 const int n = nums.size();
6735 vector dp(n, map<unsigned, unsigned>());//dp[i][j] = number of increasing subsequence end with i, length is j
6736 for(int i = 0; i < n; i++) {
6737 dp[i][1] = 1;
6738 }
6739 unsigned max_len = 1;
6740 for(int i = 0; i < n; i++) {
6741 for(int j = i + 1; j < n; j++) {
6742 auto &[len, cnt] = *dp[i].rbegin();
6743 if(nums[j] > nums[i]) {
6744 dp[j][len + 1] += cnt;
6745 max_len = max(max_len, len + 1);
6746 }
6747 }
6748 }
6749 unsigned ans = 0;
6750 for(int i = 0; i < n; i++) {
6751 ans += dp[i][max_len];
6752 }
6753 return ans;
6754 }
6755 }// namespace number_of_longest_increasing_subsequence
6756
6757 namespace longest_common_subsequence {
6758 int Solution::longestCommonSubsequence(string text1, string text2) {
6759 vector dp(text1.length(), vector(text2.length(), 0));
6760 for(int i = 0; i < text1.length(); i++) {
6761 for(int j = 0; j < text2.length(); j++) {
6762 if(text1[i] == text2[j]) {
6763 dp[i][j] = (i - 1 < 0 || j - 1 < 0 ? 0 : dp[i - 1][j - 1]) + 1;
6764 } else {
6765 dp[i][j] = max(i - 1 >= 0 ? dp[i - 1][j] : 0, j - 1 >= 0 ? dp[i][j - 1] : 0);
6766 }
6767 }
6768 }
6769 return dp.back().back();
6770 }
6771 }// namespace longest_common_subsequence
6772
6773 namespace delete_operation_for_two_strings {
6774 int Solution::minDistance(const string &word1, const string &word2) {
6776 return word1.length() + word2.length() - 2 * lcs;
6777 }
6778 }// namespace delete_operation_for_two_strings
6779
6780 namespace edit_distance {
6781 int Solution::minDistance(string word1, string word2) {
6782 // dp[i][j] is the minimum number of operations required to convert word1[0..i] to word2[0..j]
6783 vector dp(word1.length() + 1, vector<int>(word2.length() + 1));
6784 // if word[i] == word2[j], dp[i][j] = dp[i-1][j-1]; else dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
6785 for(int j = 0; j <= word2.length(); j++) {
6786 dp[0][j] = j;
6787 }
6788 for(int i = 0; i <= word1.length(); i++) {
6789 dp[i][0] = i;
6790 }
6791 for(int i = 1; i <= word1.length(); i++) {
6792 for(int j = 1; j <= word2.length(); j++) {
6793 if(word1[i - 1] == word2[j - 1]) {
6794 dp[i][j] = dp[i - 1][j - 1];
6795 } else {
6796 dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
6797 }
6798 }
6799 }
6800 return dp.back().back();
6801 }
6802 }// namespace edit_distance
6803
6804 namespace coin_change {
6805 int Solution::coinChange(vector<int> &coins, int amount) {
6806 vector dp(amount + 1, -1);
6807 dp[0] = 0;
6808 for(const auto &coin: coins) {
6809 if(coin <= amount) {
6810 dp[coin] = 1;
6811 }
6812 }
6813 for(unsigned i = 0; i <= amount; i++) {
6814 if(dp[i] > 0) {
6815 for(const auto &coin: coins) {
6816 if(i + coin <= static_cast<unsigned>(amount)) {
6817 if(dp[i + coin] == -1) {
6818 dp[i + coin] = dp[i] + 1;
6819 } else {
6820 dp[i + coin] = min(dp[i + coin], dp[i] + 1);
6821 }
6822 }
6823 }
6824 }
6825 }
6826 return dp[amount];
6827 }
6828 }// namespace coin_change
6829
6830 namespace integer_break {
6832 // dp[i] is the maximum product of i
6833 vector<int> dp(n + 1);
6834 // dp[i] = max(dp[i], dp[j] * dp[i - j])
6835 dp[2] = 1;
6836 dp[1] = 1;
6837 for(int i = 3; i <= n; i++) {
6838 for(int j = 1; j < i; j++) {
6839 dp[i] = max(dp[i], dp[j] * dp[i - j]);
6840 dp[i] = max(dp[i], j * dp[i - j]);
6841 dp[i] = max(dp[i], dp[j] * (i - j));
6842 dp[i] = max(dp[i], j * (i - j));
6843 }
6844 }
6845 return dp[n];
6846 }
6847 }// namespace integer_break
6848
6849 namespace max_points_on_a_line {
6850 int Solution::maxPoints(vector<vector<int>> &points) {
6851 int ans = 0;
6852 for(auto &p1: points) {
6853 unordered_map<long double, int> us;
6854 int cnt = 0;
6855 for(auto &p2: points) {
6856 if(p2[0] != p1[0]) {
6857 us[static_cast<long double>(p2[1] - p1[1]) / static_cast<long double>(p2[0] - p1[0])]++;
6858 } else {
6859 cnt++;
6860 }
6861 }
6862 for(auto &[k, v]: us) {
6863 cnt = max(cnt, v + 1);
6864 }
6865 ans = max(ans, cnt);
6866 }
6867 return ans;
6868 }
6869 }// namespace max_points_on_a_line
6870
6871 namespace group_anagrams {
6872 vector<vector<string>> Solution::groupAnagrams(vector<string> &strs) {
6873 vector<string> strs_sorted = strs;
6874 unordered_map<string, vector<string>> um;
6875 for(auto &str: strs_sorted) {
6876 sort(str.begin(), str.end());
6877 if(!um.contains(str)) {
6878 um[str] = vector<string>();
6879 }
6880 }
6881 for(int i = 0; i < strs.size(); i++) {
6882 um[strs_sorted[i]].emplace_back(strs[i]);
6883 }
6884 vector<vector<string>> ans;
6885 ans.reserve(um.size());
6886 for(auto &[k, v]: um) {
6887 ans.emplace_back(v);
6888 }
6889 return ans;
6890 }
6891 }// namespace group_anagrams
6892
6893 namespace sort_colors {
6894 void Solution::sortColors(vector<int> &nums) { qsort(nums, 0, nums.size() - 1); }
6895
6896 void Solution::qsort(vector<int> &nums, int l, int r) {
6897 if(l >= r) {
6898 return;
6899 }
6900 int lp = l - 1;
6901 int rp = r + 1;
6902 const int pivot = nums[(l + r) / 2];
6903 while(lp < rp) {
6904 while(nums[++lp] < pivot) {}
6905 while(nums[--rp] > pivot) {}
6906 if(lp < rp) {
6907 swap(nums[lp], nums[rp]);
6908 }
6909 }
6910 qsort(nums, l, rp);
6911 qsort(nums, rp + 1, r);
6912 }
6913 }// namespace sort_colors
6914
6915 namespace top_k_frequent_elements {
6916 vector<int> Solution::topKFrequent(vector<int> &nums, int k) {
6917 unordered_map<int, int> um;
6918 for(auto num: nums) {
6919 um[num]++;
6920 }
6921 vector<int> vec(um.size());
6922 int i = 0;
6923 for(auto &[_, v]: um) {
6924 vec[i++] = v;
6925 }
6926 sort(vec.rbegin(), vec.rend());
6927 unordered_set<int> us;
6928 for(i = 0; i < k; i++) {
6929 us.insert(vec[i]);
6930 }
6931 vector<int> ans;
6932 for(auto [num, v]: um) {
6933 if(us.contains(v)) {
6934 ans.emplace_back(num);
6935 }
6936 }
6937 return ans;
6938 }
6939 }// namespace top_k_frequent_elements
6940
6941 namespace kth_largest_element_in_an_array {
6942 int Solution::findKthLargest(vector<int> &nums, int k) {
6943 sort(nums.rbegin(), nums.rend());
6944 return nums[k - 1];
6945 }
6946 }// namespace kth_largest_element_in_an_array
6947
6948 namespace merge_intervals {
6949 vector<vector<int>> Solution::merge(vector<vector<int>> &intervals) {
6950 vector<vector<int>> ans;
6951 auto comp = [](const vector<int> &a, const vector<int> &b) { return a[0] < b[0]; };
6952 sort(intervals.begin(), intervals.end(), comp);
6953 int start = intervals[0][0];
6954 int end = intervals[0][1];
6955 for(int i = 1; i < intervals.size(); i++) {
6956 if(intervals[i][0] <= end) {
6957 end = max(end, intervals[i][1]);
6958 } else {
6959 ans.emplace_back(vector{start, end});
6960 start = intervals[i][0];
6961 end = intervals[i][1];
6962 }
6963 }
6964 ans.emplace_back(vector{start, end});
6965 return ans;
6966 }
6967 }// namespace merge_intervals
6968
6969 namespace search_a_2d_matrix_ii {
6970 bool Solution::searchMatrix(vector<vector<int>> &matrix, int target) { return search(matrix, target, 0, matrix.size() - 1, 0, matrix[0].size() - 1); }
6971
6972 bool Solution::search(const vector<vector<int>> &matrix, int target, int x_start, int x_end, int y_start, int y_end) {
6973 const int minimum = min(x_end - x_start, y_end - y_start);
6974 vector<int> diag1(minimum + 1);
6975 for(int i = 0; i <= minimum; i++) {
6976 diag1[i] = matrix[x_start + i][y_start + i];
6977 }
6978 const auto it = lower_bound(diag1.begin(), diag1.end(), target);
6979 const int x = x_start + it - diag1.begin();
6980 const int y = y_start + it - diag1.begin();
6981 if(it != diag1.end()) {
6982 if(*it == target) {
6983 return true;
6984 }
6985 if(it == diag1.begin()) {
6986 return false;
6987 }
6988 if(search(matrix, target, x_start, x - 1, y, y_end)) {
6989 return true;
6990 }
6991 if(search(matrix, target, x, x_end, y_start, y - 1)) {
6992 return true;
6993 }
6994 if(search(matrix, target, x, x_end, y, y_end)) {
6995 return true;
6996 }
6997 } else {
6998 if(x > x_end && y > y_end) {
6999 return false;
7000 }
7001 if(x > x_end && search(matrix, target, x_start, x_end, y, y_end)) {
7002 return true;
7003 }
7004 if(y > y_end && search(matrix, target, x, x_end, y_start, y_end)) {
7005 return true;
7006 }
7007 }
7008 return false;
7009 }
7010 }// namespace search_a_2d_matrix_ii
7011
7012 namespace serialize_and_deserialize_binary_tree {
7014 if(root == nullptr) {
7015 return "[]";
7016 }
7017 vector<string> vec;
7018 ostringstream oss;
7019 oss << '[';
7020 queue<TreeNode *> q;
7021 q.push(root);
7022 while(!q.empty()) {
7023 const TreeNode *node = q.front();
7024 q.pop();
7025 if(node == nullptr) {
7026 vec.emplace_back("null");
7027 continue;
7028 }
7029 vec.emplace_back(to_string(node->val));
7030 q.push(node->left);
7031 q.push(node->right);
7032 }
7033 int end = vec.size() - 1;
7034 while(vec[end] == "null" && end > 0) {
7035 end--;
7036 }
7037 oss << vec[0];
7038 for(int i = 1; i <= end; i++) {
7039 oss << ',' << vec[i];
7040 }
7041 oss << ']';
7042 return oss.str();
7043 }
7044
7046 if(data == "[]") {
7047 return nullptr;
7048 }
7049 vector<string> vec;
7050 data = data.substr(1, data.size() - 2);
7051 auto *const str = static_cast<char *>(malloc((data.length() + 1) * sizeof(char)));
7052 memcpy(str, data.c_str(), (data.length() + 1) * sizeof(char));
7053 for(const char *item = strtok(str, ","); item != nullptr; item = strtok(nullptr, ",")) {
7054 vec.emplace_back(string(item));
7055 }
7056 queue<TreeNode **> q;
7057 auto *root = new TreeNode(stoi(vec[0]));
7058 q.push(&root);
7059 for(const auto &str: vec) {
7060 auto *const node = q.front();
7061 q.pop();
7062 if(str == "null") {
7063 *node = nullptr;
7064 } else {
7065 *node = new TreeNode(stoi(str));
7066 q.push(&(*node)->left);
7067 q.push(&(*node)->right);
7068 }
7069 }
7070 return root;
7071 }
7072 }// namespace serialize_and_deserialize_binary_tree
7073
7074 namespace task_scheduler {
7075 int Solution::leastInterval(vector<char> &tasks, int n) {
7076 if(n == 0) {
7077 return tasks.size();
7078 }
7079 int maximum = 0;
7080 int cycle = 0;
7081 unordered_map<char, int> task_cnt;
7082 unordered_map<char, int> processing;
7083 for(char task: tasks) {
7084 task_cnt[task]++;
7085 }
7086 while(true) {
7087 bool finished = true;
7088 maximum = 0;
7089 for(const auto &[task, cnt]: task_cnt) {
7090 if(cnt > 0) {
7091 finished = false;
7092 }
7093 if(processing[task] <= 0) {
7094 maximum = max(maximum, cnt);
7095 }
7096 }
7097 if(finished) {
7098 return cycle;
7099 }
7100 for(auto &[task, rest]: processing) {
7101 rest--;
7102 }
7103 for(auto &[task, cnt]: task_cnt) {
7104 if(maximum == cnt && processing[task] <= 0) {
7105 cnt--;
7106 processing[task] = n;
7107 break;
7108 }
7109 }
7110 cycle++;
7111 }
7112 }
7113 }// namespace task_scheduler
7114
7115 namespace design_hashmap {
7117 arr = array<list<pair<int, int>>, SZ>();
7118 for(unsigned i = 0; i < SZ; i++) {
7119 arr[i] = list<pair<int, int>>();
7120 }
7121 }
7122
7123 void MyHashMap::put(int key, int value) {
7124 const unsigned slot = static_cast<unsigned>(key) % SZ;
7125 for(auto &[k, v]: arr[slot]) {
7126 if(k == key) {
7127 v = value;
7128 return;
7129 }
7130 }
7131 arr[slot].emplace_back(key, value);
7132 }
7133
7134 int MyHashMap::get(int key) {
7135 const unsigned slot = static_cast<unsigned>(key) % SZ;
7136 for(auto &[k, v]: arr[slot]) {
7137 if(k == key) {
7138 return v;
7139 }
7140 }
7141 return -1;
7142 }
7143
7144 void MyHashMap::remove(int key) {
7145 const unsigned slot = static_cast<unsigned>(key) % SZ;
7146 for(auto it = arr[slot].begin(); it != arr[slot].end(); ++it) {
7147 if(it->first == key) {
7148 arr[slot].erase(it);
7149 return;
7150 }
7151 }
7152 }
7153 }// namespace design_hashmap
7154
7155 namespace spiral_matrix_ii {
7156 vector<vector<int>> Solution::generateMatrix(int n) {
7157 vector ans(n, vector(n, 0));
7158 int dir = 0;// 0-right 1-down 2-left 3->up
7159 int c = 1;
7160 int x = 0;
7161 int y = 0;
7162 for(int i = 0; i < n * n; i++) {
7163 ans[x][y] = c++;
7164 bool flag = true;
7165 SLCT:
7166 int nx = x;
7167 int ny = y;
7168 switch(dir) {
7169 case 0:
7170 ny++;
7171 break;
7172 case 1:
7173 nx++;
7174 break;
7175 case 2:
7176 ny--;
7177 break;
7178 case 3:
7179 nx--;
7180 break;
7181 }
7182 if(flag && (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] != 0)) {
7183 dir++;
7184 dir %= 4;
7185 flag = false;
7186 goto SLCT;
7187 }
7188 x = nx;
7189 y = ny;
7190 }
7191 return ans;
7192 }
7193 }// namespace spiral_matrix_ii
7194
7195 namespace non_overlapping_intervals {
7196 int Solution::eraseOverlapIntervals(vector<vector<int>> &intervals) {
7197 if(intervals.empty()) {
7198 return 0;
7199 }
7200
7201 sort(intervals.begin(), intervals.end(), [](const auto &u, const auto &v) { return u[1] < v[1]; });
7202
7203 const int n = intervals.size();
7204 int right = intervals[0][1];
7205 int ans = 1;
7206 for(int i = 1; i < n; ++i) {
7207 if(intervals[i][0] >= right) {
7208 ++ans;
7209 right = intervals[i][1];
7210 }
7211 }
7212 return n - ans;
7213 }
7214 }// namespace non_overlapping_intervals
7215
7216 namespace product_of_array_except_self {
7217 vector<int> Solution::productExceptSelf(vector<int> &nums) {
7218 vector<int> left(nums.size());
7219 vector<int> right(nums.size());
7220 int c = 1;
7221 for(int i = 0; i < left.size(); i++) {
7222 left[i] = c;
7223 c *= nums[i];
7224 }
7225 c = 1;
7226 for(int i = left.size() - 1; i >= 0; i--) {
7227 right[i] = c;
7228 c *= nums[i];
7229 }
7230 vector<int> ans(nums.size());
7231 for(int i = 0; i < nums.size(); i++) {
7232 ans[i] = left[i] * right[i];
7233 }
7234 return ans;
7235 }
7236 }// namespace product_of_array_except_self
7237
7238 namespace subarray_sum_equals_k {
7239 int Solution::subarraySum(vector<int> &nums, int k) {
7240 unordered_map<int, int> um;
7241 um[0] = 1;
7242 int count = 0;
7243 int ps = 0;
7244 for(const auto &num: nums) {
7245 ps += num;
7246 count += um[ps - k];
7247 um[ps]++;
7248 }
7249 return count;
7250 }
7251 }// namespace subarray_sum_equals_k
7252
7253 namespace partition_labels {
7254 vector<int> Solution::partitionLabels(string s) {
7255 unordered_map<char, unsigned> last;
7256 vector<int> ans;
7257 for(int i = 0; i < s.length(); i++) {
7258 last[s[i]] = i;
7259 }
7260 for(int i = 0; i < s.length();) {
7261 unsigned last_pos = i;
7262 char ch = s[i];
7263 for(int j = i; j <= last_pos; j++) {
7264 last_pos = max(last_pos, last[s[j]]);
7265 }
7266 ans.emplace_back(last_pos - i + 1);
7267 i = last_pos + 1;
7268 }
7269 return ans;
7270 }
7271 }// namespace partition_labels
7272
7273 namespace repeated_dna_sequences {
7274 vector<string> Solution::findRepeatedDnaSequences(string s) {
7275 vector<unsigned short> vec(s.length());
7276 for(int i = 0; i < s.length(); i++) {
7277 switch(s[i]) {
7278 case 'A':
7279 vec[i] = 0;
7280 break;
7281 case 'C':
7282 vec[i] = 1;
7283 break;
7284 case 'G':
7285 vec[i] = 2;
7286 break;
7287 case 'T':
7288 vec[i] = 3;
7289 break;
7290 }
7291 }
7292 unsigned hsv = 0;
7293 if(s.length() < 10) {
7294 return {};
7295 }
7296 unordered_map<unsigned, string> um;
7297 unordered_map<unsigned, unsigned> cnt;
7298 for(int i = 0; i < 10; i++) {
7299 hsv *= 4;
7300 hsv += vec[i];
7301 }
7302 um[hsv] = s.substr(0, 10);
7303 cnt[hsv] = 1;
7304 const unsigned f = 262144;
7305 for(int i = 10; i < s.length(); i++) {
7306 hsv -= vec[i - 10] * f;
7307 hsv *= 4;
7308 hsv += vec[i];
7309 um[hsv] = s.substr(i - 9, 10);
7310 cnt[hsv]++;
7311 }
7312 vector<string> ans;
7313 for(auto &[k, v]: um) {
7314 if(cnt[k] > 1) {
7315 ans.emplace_back(v);
7316 }
7317 }
7318 return ans;
7319 }
7320 }// namespace repeated_dna_sequences
7321
7322 namespace design_linked_list {
7324 head = new ListNode();
7325 tail = head;
7326 }
7327
7328 int MyLinkedList::get(int index) const {
7329 index += 1;
7330 if(index < 1) {
7331 return -1;
7332 }
7333 const ListNode *current = head;
7334 for(int i = 0; i < index && current != nullptr; i++) {
7335 current = current->next;
7336 }
7337 return current == nullptr ? -1 : current->val;
7338 }
7339
7341 auto *const node = new ListNode(val);
7342 node->next = head->next;
7343 head->next = node;
7344 if(tail == head) {
7345 tail = node;
7346 }
7347 }
7348
7350 auto *const node = new ListNode(val);
7351 tail->next = node;
7352 tail = node;
7353 }
7354
7355 void MyLinkedList::addAtIndex(int index, int val) {
7356 index += 1;
7357 if(index < 1) {
7358 return;
7359 }
7360 auto *const node = new ListNode(val);
7361 ListNode *current = head;
7362 for(int i = 0; i < index - 1 && current != nullptr; i++) {
7363 current = current->next;
7364 }
7365 if(current == nullptr) {
7366 delete node;
7367 return;
7368 }
7369 node->next = current->next;
7370 current->next = node;
7371 if(current == tail) {
7372 tail = node;
7373 }
7374 }
7375
7377 index += 1;
7378 if(index < 1) {
7379 return;
7380 }
7381 ListNode *current = head;
7382 for(int i = 0; i < index - 1 && current != nullptr; i++) {
7383 current = current->next;
7384 }
7385 if(current == nullptr) {
7386 return;
7387 }
7388 const auto *const p = current->next;
7389 if(p == tail) {
7390 tail = current;
7391 }
7392 if(p != nullptr) {
7393 current->next = current->next->next;
7394 delete p;
7395 }
7396 }
7397 }// namespace design_linked_list
7398
7399 namespace delete_node_in_a_bst {
7401 TreeNode *current = node;
7402 while(current->right != nullptr) {
7403 prev = current;
7404 current = current->right;
7405 }
7406 return current;
7407 }
7408
7410 TreeNode *current = node;
7411 while(current->left != nullptr) {
7412 prev = current;
7413 current = current->left;
7414 }
7415 return current;
7416 }
7417
7419 if(node->right != nullptr) {
7420 prev = node;
7421 auto *const rmin = findMinimum(node->right);
7422 node->val = rmin->val;
7423 remove(rmin);
7424 return;
7425 }
7426 if(node->left != nullptr) {
7427 prev = node;
7428 auto *const lmax = findMaximum(node->left);
7429 node->val = lmax->val;
7430 remove(lmax);
7431 return;
7432 }
7433 if(prev != nullptr) {
7434 if(prev->left != nullptr && prev->left->val == node->val) {
7435 prev->left = nullptr;
7436 } else if(prev->right != nullptr && prev->right->val == node->val) {
7437 prev->right = nullptr;
7438 }
7439 } else {
7440 exit(-1);
7441 }
7442 //delete node;
7443 }
7444
7446 if(root == nullptr) {
7447 return root;
7448 }
7449 TreeNode *current = root;
7450 while(current != nullptr && current->val != key) {
7451 if(current->val == key) {
7452 break;
7453 }
7454 prev = current;
7455 if(current->val < key) {
7456 current = current->right;
7457 } else {
7458 current = current->left;
7459 }
7460 }
7461 if(current == nullptr) {
7462 return root;
7463 }
7464 if(root->left == nullptr && root->right == nullptr) {
7465 return nullptr;
7466 }
7467 remove(current);
7468 return root;
7469 }
7470 }// namespace delete_node_in_a_bst
7471
7472 namespace missing_element_in_sorted_array {
7473 int Solution::missingElement(vector<int> &nums, int k) {
7474 unordered_set<int> us;
7475 for(auto num: nums) {
7476 us.insert(num);
7477 }
7478 if(missing(nums, nums.size() - 1) < k) {
7479 return nums[0] + k + nums.size() - 1;
7480 }
7481 int l = 0;
7482 int r = nums.size() - 1;
7483 while(l < r) {
7484 if(r == l + 1) {
7485 return nums[l] + k - missing(nums, l);
7486 }
7487 const int m = (l + r) / 2;
7488 if(missing(nums, m) < k) {
7489 l = m;
7490 } else if(missing(nums, m) >= k) {
7491 r = m;
7492 }
7493 }
7494 return 0;
7495 }
7496
7497 unsigned Solution::missing(vector<int> &nums, int i) { return nums[i] - nums[0] - i; }
7498 }// namespace missing_element_in_sorted_array
7499
7500 namespace find_a_peak_element_ii {
7501 vector<int> Solution::findPeakGridLR(vector<vector<int>> &mat, int l, int r) {
7502 const int mid = (l + r) / 2;
7503 int max_col = mid;
7504 int max_row = 0;
7505 int maximum = -1;
7506 for(int i = 0; i < mat.size(); i++) {
7507 for(int j = mid - 1; j <= mid + 1; j++) {
7508 if(maximum < get(mat, i, j)) {
7509 maximum = get(mat, i, j);
7510 max_col = j;
7511 max_row = i;
7512 }
7513 }
7514 }
7515 if(max_col == mid || l + 1 == r) {
7516 return {max_row, max_col};
7517 }
7518 if(max_col == mid + 1) {
7519 return findPeakGridLR(mat, mid, r);
7520 }
7521 return findPeakGridLR(mat, l, mid);
7522 }
7523
7524 vector<int> Solution::findPeakGrid(vector<vector<int>> &mat) { return findPeakGridLR(mat, 0, mat[0].size() - 1); }
7525
7526 int Solution::get(vector<vector<int>> &mat, int i, int j) {
7527 if(i >= 0 && i < mat.size() && j >= 0 && j < mat[0].size()) {
7528 return mat[i][j];
7529 }
7530 return -1;
7531 }
7532 }// namespace find_a_peak_element_ii
7533
7534 namespace divide_chocolate {
7535 int Solution::maximizeSweetness(vector<int> &sweetness, int k) {
7536 int l = sweetness[0];
7537 int r = 0;
7538 for(auto s: sweetness) {
7539 l = min(l, s);
7540 r += s;
7541 }
7542 while(l < r) {
7543 if(l + 1 == r) {
7544 return count(sweetness, r) == k + 1 ? r : l;
7545 }
7546 const int m = (l + r) / 2;
7547 const int c = count(sweetness, m);
7548 if(c < k + 1) {
7549 r = m - 1;
7550 } else {
7551 l = m;
7552 }
7553 }
7554 return l;
7555 }
7556
7557 int Solution::count(vector<int> &sweetness, int x) {
7558 int ans = 0;
7559 int current = 0;
7560 for(const auto s: sweetness) {
7561 current += s;
7562 if(current >= x) {
7563 current = 0;
7564 ans++;
7565 }
7566 }
7567 return ans;
7568 }
7569 }// namespace divide_chocolate
7570
7571 namespace shortest_distance_to_target_color {
7572 vector<int> Solution::shortestDistanceColor(vector<int> &colors, vector<vector<int>> &queries) {
7573 vector<int> ans;
7574 unordered_map<int, vector<int>> um;
7575 for(int i = 0; i < colors.size(); i++) {
7576 um[colors[i]].emplace_back(i);
7577 }
7578 for(auto &[k, vec]: um) {
7579 sort(vec.begin(), vec.end());
7580 }
7581 for(auto &query: queries) {
7582 int &i = query[0];
7583 int &c = query[1];
7584 vector<int> &vec = um[c];
7585 auto g = lower_bound(vec.begin(), vec.end(), i, less());
7586 auto l = lower_bound(vec.rbegin(), vec.rend(), i, greater());
7587 if(g == vec.end() && l == vec.rend()) {
7588 ans.emplace_back(-1);
7589 } else if(g == vec.end()) {
7590 ans.emplace_back(abs(*l - i));
7591 } else if(l == vec.rend()) {
7592 ans.emplace_back(abs(*g - i));
7593 } else {
7594 ans.emplace_back(min(abs(*l - i), abs(*g - i)));
7595 }
7596 }
7597 return ans;
7598 }
7599 }// namespace shortest_distance_to_target_color
7600
7601 namespace meeting_scheduler {
7602 vector<int> Solution::minAvailableDuration(vector<vector<int>> &slots1, vector<vector<int>> &slots2, int duration) {
7603 vector<int> ans(2);
7604 auto cmp = [](const vector<int> &vec1, const vector<int> &vec2) -> bool {
7605 if(vec1[1] != vec2[1]) {
7606 return vec1[1] < vec2[1];
7607 }
7608 return vec1[0] < vec2[0];
7609 };
7610 sort(slots1.begin(), slots1.end(), cmp);
7611 sort(slots2.begin(), slots2.end(), cmp);
7612 for(auto it1 = slots1.begin(), it2 = slots2.begin(); it1 != slots1.end() && it2 != slots2.end();) {
7613 pair<int, int> p = merge(*it1, *it2);
7614 if(p.second - p.first >= duration) {
7615 return {p.first, p.first + duration};
7616 }
7617 if(cmp(*it1, *it2)) {
7618 ++it1;
7619 } else {
7620 ++it2;
7621 }
7622 }
7623 return {};
7624 }
7625
7626 pair<int, int> Solution::merge(const vector<int> &vec1, const vector<int> &vec2) { return {max(vec1[0], vec2[0]), min(vec1[1], vec2[1])}; }
7627 }// namespace meeting_scheduler
7628
7629 namespace find_the_duplicate_number {
7630 int Solution::findDuplicate(vector<int> &nums) {
7631 int maximum = nums[0];
7632 int minimum = nums[0];
7633 for(const auto &num: nums) {
7634 maximum = max(maximum, num);
7635 minimum = min(minimum, num);
7636 }
7637 int l = minimum;
7638 int r = maximum;
7639 while(l < r) {
7640 const int m = (l + r) / 2;
7641 const int c = countInRange(nums, l, m);
7642 if(c == m - l + 1) {
7643 l = m + 1;
7644 } else if(c > m - l + 1) {
7645 r = m;
7646 } else {
7647 l++;
7648 }
7649 }
7650 return l;
7651 }
7652
7653 int Solution::countInRange(vector<int> &nums, int l, int r) {
7654 int ans = 0;
7655 for(const auto &num: nums) {
7656 if(l <= num && num <= r) {
7657 ans++;
7658 }
7659 }
7660 return ans;
7661 }
7662 }// namespace find_the_duplicate_number
7663
7664 namespace trapping_rain_water {
7665 int Solution::trap(vector<int> &height) {
7666 vector lmax(height.size(), 0);
7667 vector rmax(height.size(), 0);
7668 int maximum = height[0];
7669 for(int i = 0; i < height.size(); i++) {
7670 maximum = max(maximum, height[i]);
7671 lmax[i] = maximum;
7672 }
7673 maximum = height.back();
7674 for(int i = height.size() - 1; i >= 0; i--) {
7675 maximum = max(maximum, height[i]);
7676 rmax[i] = maximum;
7677 }
7678 int ans = 0;
7679 for(int i = 0; i < height.size(); i++) {
7680 ans += min(lmax[i], rmax[i]) - height[i];
7681 }
7682 return ans;
7683 }
7684 }// namespace trapping_rain_water
7685
7686 namespace product_of_two_run_length_encoded_arrays {
7687 vector<vector<int>> Solution::findRLEArray(vector<vector<int>> &encoded1, vector<vector<int>> &encoded2) {
7688 vector<vector<int>> ans;
7689 int p1 = 0;
7690 int p2 = 0;
7691 for(int i1 = 0, i2 = 0; i1 < encoded1.size() && i2 < encoded2.size();) {
7692 const int len = min(encoded1[i1][1] - p1, encoded2[i2][1] - p2);
7693 const int v = encoded1[i1][0] * encoded2[i2][0];
7694 if(!ans.empty() && ans.back()[0] == v) {
7695 ans.back()[1] += len;
7696 } else {
7697 vector vec = {v, len};
7698 ans.emplace_back(vec);
7699 }
7700 p1 += len;
7701 p2 += len;
7702 if(p1 >= encoded1[i1][1]) {
7703 i1++;
7704 p1 = 0;
7705 }
7706 if(p2 >= encoded2[i2][1]) {
7707 i2++;
7708 p2 = 0;
7709 }
7710 }
7711 return ans;
7712 }
7713 }// namespace product_of_two_run_length_encoded_arrays
7714
7715 namespace longest_substring_with_at_most_two_distinct_characters {
7716 int Solution::getMinUniqueCharCnt(const string &s, int len) {
7717 unordered_map<char, int> um;
7718 for(int i = 0; i < len; i++) {
7719 um[s[i]]++;
7720 }
7721 size_t ans = um.size();
7722 for(int i = 0, j = len; j < s.length(); i++, j++) {
7723 um[s[i]]--;
7724 um[s[j]]++;
7725 if(um[s[i]] == 0) {
7726 um.erase(s[i]);
7727 }
7728 ans = min(ans, um.size());
7729 }
7730 return ans;
7731 }
7732
7734 int l = 1;
7735 int r = s.length();
7736 while(l < r) {
7737 const int mid = (l + r) / 2 + 1;
7738 const int res = getMinUniqueCharCnt(s, mid);
7739 if(res > 2) {
7740 r = mid - 1;
7741 } else {
7742 l = mid;
7743 }
7744 }
7745 return l;
7746 }
7747 }// namespace longest_substring_with_at_most_two_distinct_characters
7748
7749 namespace longest_substring_with_at_most_k_distinct_characters {
7751 if(k == 0) {
7752 return 0;
7753 }
7754 int l = 1;
7755 int r = s.length();
7756 while(l < r) {
7757 const int mid = (l + r) / 2 + 1;
7759 if(res > k) {
7760 r = mid - 1;
7761 } else {
7762 l = mid;
7763 }
7764 }
7765 return l;
7766 }
7767 }// namespace longest_substring_with_at_most_k_distinct_characters
7768
7769 namespace max_consecutive_ones_iii {
7770 int Solution::longestOnes(vector<int> &nums, int k) {
7771 int l = 0;
7772 int r = nums.size();
7773 while(l < r) {
7774 const int mid = (l + r) / 2 + 1;
7775 const int res = cntMinFlip(nums, mid);
7776 if(res > k) {
7777 r = mid - 1;
7778 } else {
7779 l = mid;
7780 }
7781 }
7782 return l;
7783 }
7784
7785 int Solution::cntMinFlip(vector<int> &nums, int len) {
7786 if(len == 0) {
7787 return 0;
7788 }
7789 int current = 0;
7790 for(int i = 0; i < len; i++) {
7791 if(nums[i] == 0) {
7792 current++;
7793 }
7794 }
7795 int ans = current;
7796 for(int i = 0, j = len; j < nums.size(); i++, j++) {
7797 if(nums[i] == 0) {
7798 current--;
7799 }
7800 if(nums[j] == 0) {
7801 current++;
7802 }
7803 ans = min(ans, current);
7804 }
7805 return ans;
7806 }
7807 }// namespace max_consecutive_ones_iii
7808
7809 namespace sliding_window_maximum {
7810 vector<int> Solution::maxSlidingWindow(vector<int> &nums, int k) {
7811 multiset<int> ms;
7812 for(int i = 0; i < k; i++) {
7813 ms.insert(nums[i]);
7814 }
7815 vector<int> ans;
7816 for(int i = 0, j = k; j < nums.size(); i++, j++) {
7817 ans.emplace_back(*ms.rbegin());
7818 ms.erase(ms.lower_bound(nums[i]));
7819 ms.insert(nums[j]);
7820 }
7821 ans.emplace_back(*ms.rbegin());
7822 return ans;
7823 }
7824 }// namespace sliding_window_maximum
7825
7826 namespace minimum_window_substring {
7827 string Solution::minWindow(string s, const string &t) {
7828 string ans = s;
7829 int l = 0;
7830 int r = 0;
7831 unordered_map<char, int> umt;
7832 unordered_map<char, int> ums;
7833 ums[s[0]]++;
7834 for(char ch: t) {
7835 umt[ch]++;
7836 }
7837 bool flag = true;
7838 while(l <= r && r < s.length() && l < s.length()) {
7839 while(!valid(ums, umt) && r + 1 < s.length()) {
7840 ums[s[++r]]++;
7841 }
7842 while(valid(ums, umt) && l < s.length()) {
7843 flag = false;
7844 if(r - l + 1 < ans.length()) {
7845 ans = s.substr(l, r - l + 1);
7846 }
7847 ums[s[l++]]--;
7848 }
7849 if(flag) {
7850 return "";
7851 }
7852 if(r == s.length() - 1) {
7853 break;
7854 }
7855 }
7856 return ans;
7857 }
7858
7859 bool Solution::valid(unordered_map<char, int> &ums, const unordered_map<char, int> &umt) {
7860 for(const auto &[k, v]: umt) {
7861 if(!ums.contains(k) || ums[k] < v) {
7862 return false;
7863 }
7864 }
7865 return true;
7866 }
7867 }// namespace minimum_window_substring
7868
7869 namespace walls_and_gates {
7870 void Solution::wallsAndGates(vector<vector<int>> &rooms) {
7871 const int m = rooms.size();
7872 const int n = rooms[0].size();
7873 queue<tuple<int, int, int>> q;
7874 for(int i = 0; i < m; i++) {
7875 for(int j = 0; j < n; j++) {
7876 if(rooms[i][j] == 0) {
7877 q.push({0, i, j});
7878 }
7879 }
7880 }
7881 while(!q.empty()) {
7882 auto [d, x, y] = q.front();
7883 q.pop();
7884 pair<int, int> nexts[4] = {{x + 1, y}, {x - 1, y}, {x, y + 1}, {x, y - 1}};
7885 for(auto &[next_x, next_y]: nexts) {
7886 if(next_x >= 0 && next_y >= 0 && next_x < m && next_y < n && rooms[next_x][next_y] != -1 && rooms[next_x][next_y] != 0 && (rooms[next_x][next_y] == INT_MAX || rooms[next_x][next_y] > d + 1)) {
7887 rooms[next_x][next_y] = d + 1;
7888 q.push({d + 1, next_x, next_y});
7889 }
7890 }
7891 }
7892 }
7893 }// namespace walls_and_gates
7894
7895 namespace pacific_atlantic_waterflow {
7896 vector<vector<int>> Solution::pacificAtlantic(vector<vector<int>> &heights) {
7897 const int m = heights.size();
7898 const int n = heights[0].size();
7899 unordered_set<pair<int, int>, myhash, myeq> pacific;
7900 unordered_set<pair<int, int>, myhash, myeq> atlantic;
7901 queue<pair<int, int>> q;
7902 vector<vector<int>> ans;
7903
7904 for(int i = 0; i < m; i++) {
7905 q.push({i, 0});
7906 pacific.insert({i, 0});
7907 }
7908 for(int i = 1; i < n; i++) {
7909 q.push({0, i});
7910 pacific.insert({0, i});
7911 }
7912 while(!q.empty()) {
7913 auto [x, y] = q.front();
7914 q.pop();
7915 pair<int, int> nexts[4] = {{x + 1, y}, {x - 1, y}, {x, y + 1}, {x, y - 1}};
7916 for(auto &[next_x, next_y]: nexts) {
7917 if(next_x >= 0 && next_y >= 0 && next_x < m && next_y < n && heights[next_x][next_y] >= heights[x][y] && !pacific.contains({next_x, next_y})) {
7918 pacific.insert({next_x, next_y});
7919 q.push({next_x, next_y});
7920 }
7921 }
7922 }
7923
7924 for(int i = 0; i < m; i++) {
7925 q.push({i, n - 1});
7926 atlantic.insert({i, n - 1});
7927 }
7928 for(int i = 0; i < n - 1; i++) {
7929 q.push({m - 1, i});
7930 atlantic.insert({m - 1, i});
7931 }
7932 while(!q.empty()) {
7933 auto [x, y] = q.front();
7934 q.pop();
7935 pair<int, int> nexts[4] = {{x + 1, y}, {x - 1, y}, {x, y + 1}, {x, y - 1}};
7936 for(auto &[next_x, next_y]: nexts) {
7937 if(next_x >= 0 && next_y >= 0 && next_x < m && next_y < n && heights[next_x][next_y] >= heights[x][y] && !atlantic.contains({next_x, next_y})) {
7938 atlantic.insert({next_x, next_y});
7939 q.push({next_x, next_y});
7940 }
7941 }
7942 }
7943
7944 for(const auto &p: atlantic) {
7945 if(pacific.contains(p)) {
7946 vector vec = {p.first, p.second};
7947 ans.emplace_back(vec);
7948 }
7949 }
7950 sort(ans.begin(), ans.end());
7951 return ans;
7952 }
7953
7954 bool myeq::operator()(const pair<int, int> &p1, const pair<int, int> &p2) const { return p1 == p2; }
7955
7956 size_t myhash::operator()(const pair<int, int> &p) const { return p.first * 200 + p.second; }
7957 }// namespace pacific_atlantic_waterflow
7958
7959 namespace find_all_the_lonely_nodes {
7961 vector<int> ans;
7962 queue<TreeNode *> q;
7963 q.push(root);
7964 while(!q.empty()) {
7965 const TreeNode *node = q.front();
7966 q.pop();
7967 if(node->left == nullptr && node->right != nullptr) {
7968 ans.emplace_back(node->right->val);
7969 } else if(node->right == nullptr && node->left != nullptr) {
7970 ans.emplace_back(node->left->val);
7971 }
7972 if(node->left != nullptr) {
7973 q.push(node->left);
7974 }
7975 if(node->right != nullptr) {
7976 q.push(node->right);
7977 }
7978 }
7979 return ans;
7980 }
7981 }// namespace find_all_the_lonely_nodes
7982
7983 namespace kill_process {
7984 vector<int> Solution::killProcess(vector<int> &pid, vector<int> &ppid, int kill) {
7985 unordered_map<int, Node *> um;
7986 for(const auto &v: pid) {
7987 um[v] = new Node(v);
7988 }
7989 for(int i = 0; i < pid.size(); i++) {
7990 if(ppid[i] != 0) {
7991 um[ppid[i]]->children.insert(um[pid[i]]);
7992 }
7993 }
7994 vector<int> ans;
7995 queue<Node *> q;
7996 q.push(um[kill]);
7997 while(!q.empty()) {
7998 Node *node = q.front();
7999 q.pop();
8000 ans.emplace_back(node->val);
8001 for(auto *next: node->children) {
8002 q.push(next);
8003 }
8004 }
8005 return ans;
8006 }
8007 }// namespace kill_process
8008
8009 namespace all_nodes_distance_k_in_binary_tree {
8010 vector<int> Solution::distanceK(TreeNode *root, TreeNode *target, int k) {
8011 if(k == 0) {
8012 return {target->val};
8013 }
8014 unordered_map<TreeNode *, Node *> um;
8015 vector<int> ans;
8016 queue<TreeNode *> q1;
8017 q1.push(root);
8018 um[root] = new Node(root->val);
8019 while(!q1.empty()) {
8020 TreeNode *tn = q1.front();
8021 q1.pop();
8022 if(tn->left != nullptr) {
8023 q1.push(tn->left);
8024 um[tn->left] = new Node(tn->left->val);
8025 um[tn->left]->siblings.insert(um[tn]);
8026 um[tn]->siblings.insert(um[tn->left]);
8027 }
8028 if(tn->right != nullptr) {
8029 q1.push(tn->right);
8030 um[tn->right] = new Node(tn->right->val);
8031 um[tn->right]->siblings.insert(um[tn]);
8032 um[tn]->siblings.insert(um[tn->right]);
8033 }
8034 }
8035 Node *node = um[target];
8036 unordered_set<Node *> vis;
8037 queue<pair<int, Node *>> q2;
8038 q2.push({0, node});
8039 while(!q2.empty()) {
8040 auto [d, nd] = q2.front();
8041 q2.pop();
8042 vis.insert(nd);
8043 for(auto *sibling: nd->siblings) {
8044 if(!vis.contains(sibling)) {
8045 vis.insert(sibling);
8046 if(d + 1 == k) {
8047 ans.emplace_back(sibling->val);
8048 } else {
8049 q2.push({d + 1, sibling});
8050 }
8051 }
8052 }
8053 }
8054 return ans;
8055 }
8056 }// namespace all_nodes_distance_k_in_binary_tree
8057
8058 namespace open_the_lock {
8059 int Solution::openLock(vector<string> &deadends, const string &target) {
8060 unordered_set<string> deads;
8061 unordered_set<string> vis;
8062 for(auto &deadend: deadends) {
8063 deads.insert(deadend);
8064 }
8065 auto get_nexts = [](const string &code) {
8066 vector ans(8, code);
8067 ans[0][0] = (ans[0][0] - '0' + 10 + 1) % 10 + '0';
8068 ans[1][0] = (ans[1][0] - '0' + 10 - 1) % 10 + '0';
8069 ans[2][1] = (ans[2][1] - '0' + 10 + 1) % 10 + '0';
8070 ans[3][1] = (ans[3][1] - '0' + 10 - 1) % 10 + '0';
8071 ans[4][2] = (ans[4][2] - '0' + 10 + 1) % 10 + '0';
8072 ans[5][2] = (ans[5][2] - '0' + 10 - 1) % 10 + '0';
8073 ans[6][3] = (ans[6][3] - '0' + 10 + 1) % 10 + '0';
8074 ans[7][3] = (ans[7][3] - '0' + 10 - 1) % 10 + '0';
8075 return ans;
8076 };
8077 queue<pair<int, string>> q;
8078 q.push({0, "0000"});
8079 while(!q.empty()) {
8080 auto [step, code] = q.front();
8081 if(code == target) {
8082 return step;
8083 }
8084 vis.insert(code);
8085 q.pop();
8086 if(deads.contains(code)) {
8087 continue;
8088 }
8089 auto nexts = get_nexts(code);
8090 for(auto &next: nexts) {
8091 if(!vis.contains(next)) {
8092 vis.insert(next);
8093 if(next == target) {
8094 return step + 1;
8095 }
8096 q.push({step + 1, next});
8097 }
8098 }
8099 }
8100 return -1;
8101 }
8102 }// namespace open_the_lock
8103
8104 namespace number_of_operations_to_make_network_connected {
8105 int Solution::makeConnected(int n, vector<vector<int>> &connections) {
8106 vector<unordered_set<int>> g(n);
8107 for(auto &connection: connections) {
8108 g[connection[0]].insert(connection[1]);
8109 g[connection[1]].insert(connection[0]);
8110 }
8111 int group_cnt = 0;
8112 int free_edges_cnt = 0;
8113 unordered_set<int> vis;
8114 for(int i = 0; i < n; i++) {
8115 if(!vis.contains(i)) {
8116 int edge_cnt = 0;
8117 int node_cnt = 0;
8118 dfs(edge_cnt, node_cnt, vis, i, g);
8119 group_cnt++;
8120 free_edges_cnt += edge_cnt / 2 - node_cnt + 1;
8121 }
8122 }
8123 if(free_edges_cnt < group_cnt - 1) {
8124 return -1;
8125 }
8126 return group_cnt - 1;
8127 }
8128
8129 void Solution::dfs(int &edge_cnt, int &node_cnt, unordered_set<int> &vis, int node, vector<unordered_set<int>> &g) {
8130 node_cnt++;
8131 edge_cnt += g[node].size();
8132 vis.insert(node);
8133 for(auto next: g[node]) {
8134 if(!vis.contains(next)) {
8135 dfs(edge_cnt, node_cnt, vis, next, g);
8136 }
8137 }
8138 }
8139 }// namespace number_of_operations_to_make_network_connected
8140
8141 namespace minimum_cost_to_make_at_least_one_valid_path_in_a_grid {
8142 int Solution::minCost(vector<vector<int>> &grid) {
8143 const int m = grid.size();
8144 const int n = grid[0].size();
8145 vector g(m, vector<Node *>(n, nullptr));
8146 for(int i = 0; i < m; i++) {
8147 for(int j = 0; j < n; j++) {
8148 g[i][j] = new Node(i, j);
8149 }
8150 }
8151 for(int i = 0; i < m; i++) {
8152 for(int j = 0; j < n; j++) {
8153 pair<int, int> nexts[4] = {{i + 1, j}, {i - 1, j}, {i, j + 1}, {i, j - 1}};
8154 for(auto [x, y]: nexts) {
8155 if(x >= 0 && x < m && y >= 0 && y < n) {
8156 g[i][j]->siblings.insert(make_pair(g[x][y], 1));
8157 }
8158 }
8159 int x = i;
8160 int y = j;
8161 switch(grid[i][j]) {
8162 case 1:
8163 y++;
8164 break;
8165 case 2:
8166 y--;
8167 break;
8168 case 3:
8169 x++;
8170 break;
8171 case 4:
8172 x--;
8173 break;
8174 }
8175 if(x >= 0 && x < m && y >= 0 && y < n) {
8176 g[i][j]->siblings[g[x][y]] = 0;
8177 }
8178 }
8179 }
8180 priority_queue<pair<int, Node *>, vector<pair<int, Node *>>, mycmp> pq;
8181 unordered_set<Node *> vis;
8182 pq.push({0, g[0][0]});
8183 while(!pq.empty()) {
8184 auto [cost, node] = pq.top();
8185 pq.pop();
8186 if(vis.contains(node)) {
8187 continue;
8188 }
8189 vis.insert(node);
8190 if(node->x == m - 1 && node->y == n - 1) {
8191 return cost;
8192 }
8193 for(auto [sibling, c]: node->siblings) {
8194 if(!vis.contains(sibling)) {
8195 pq.push({cost + c, sibling});
8196 }
8197 }
8198 }
8199 return 0;
8200 }
8201
8202 bool mycmp::operator()(const pair<int, Node *> &p1, const pair<int, Node *> &p2) const {
8203 if(p1.first != p2.first) {
8204 return p1.first > p2.first;
8205 }
8206 return p1.second->x + p1.second->y < p2.second->x + p2.second->y;
8207 }
8208 }// namespace minimum_cost_to_make_at_least_one_valid_path_in_a_grid
8209
8210 namespace critical_connections_in_a_network {
8211 vector<vector<int>> Solution::criticalConnections(int n, vector<vector<int>> &connections) {
8212 vector<unordered_set<int>> g(n);
8213 for(auto &conn: connections) {
8214 g[conn[0]].insert(conn[1]);
8215 g[conn[1]].insert(conn[0]);
8216 }
8217 vector<vector<int>> ans;
8218 vector dfn(n, -1);
8219 vector low(n, -1);
8220 unordered_set<int> vis;
8221 int step = 0;
8222 for(int i = 0; i < n; i++) {
8223 if(dfn[i] == -1) {
8224 step = 0;
8225 tarjan(-1, step, dfn, i, g, low, ans);
8226 }
8227 }
8228 return ans;
8229 }
8230
8231 void Solution::tarjan(int prev, int &step, vector<int> &dfn, int node, vector<unordered_set<int>> &g, vector<int> &low, vector<vector<int>> &ans) {
8232 dfn[node] = step;
8233 low[node] = step;
8234 for(const auto &next: g[node]) {
8235 if(dfn[next] == -1) {
8236 tarjan(node, ++step, dfn, next, g, low, ans);
8237 }
8238 if(next != prev) {
8239 low[node] = min(low[node], low[next]);
8240 }
8241 if(dfn[node] < low[next]) {
8242 ans.push_back({node, next});
8243 }
8244 }
8245 }
8246 }// namespace critical_connections_in_a_network
8247
8248 namespace factor_combinations {
8249 vector<vector<int>> Solution::getFactorsWithMin(int n, int minimum) {
8250 vector<vector<int>> ans;
8251 for(int i = minimum; i <= sqrt(n); i++) {
8252 if(n % i == 0) {
8253 ans.push_back({i, n / i});
8254 auto res = getFactorsWithMin(n / i, i);
8255 for(auto &vec: res) {
8256 ans.push_back({i});
8257 ans.back().insert(ans.back().end(), vec.begin(), vec.end());
8258 }
8259 }
8260 }
8261 return ans;
8262 }
8263
8264 vector<vector<int>> Solution::getFactors(int n) { return getFactorsWithMin(n, 2); }
8265 }// namespace factor_combinations
8266
8267 namespace decode_string {
8268 string Solution::decodeString(string s) {
8269 int i = 0;
8270 vector<int> cnt;
8271 vector<string> strs;
8272 while(i < s.length()) {
8273 if(isalpha(s[i]) != 0) {
8274 cnt.emplace_back(1);
8275 strs.emplace_back(string(1, s[i]));
8276 i++;
8277 } else if(isdigit(s[i]) != 0) {
8278 int j = i + 1;
8279 while(j < s.length() && isdigit(s[j]) != 0) {
8280 j++;
8281 }
8282 cnt.emplace_back(stoi(s.substr(i, j - i)));
8283 i = j;
8284 int level = 1;
8285 while(level > 0) {
8286 j++;
8287 if(s[j] == '[') {
8288 level++;
8289 } else if(s[j] == ']') {
8290 level--;
8291 }
8292 }
8293 strs.emplace_back(decodeString(s.substr(i + 1, j - i - 1)));
8294 i = j + 1;
8295 }
8296 }
8297 ostringstream oss;
8298 for(i = 0; i < cnt.size(); i++) {
8299 for(int j = 0; j < cnt[i]; j++) {
8300 oss << strs[i];
8301 }
8302 }
8303 return oss.str();
8304 }
8305 }// namespace decode_string
8306
8307 namespace n_queens {
8308 vector<vector<string>> Solution::solveNQueens(int n) {
8309 vector<vector<string>> ans;
8310 const vector board(n, vector(n, false));
8311 dfs(board, 0, n, ans);
8312 return ans;
8313 }
8314
8315 void Solution::dfs(const vector<vector<bool>> &board, int line, int n, vector<vector<string>> &ans) {
8316 if(line == n) {
8317 ans.emplace_back(toStringVec(board));
8318 return;
8319 }
8320 for(int i = 0; i < n; i++) {
8321 if(valid(board, n, line, i)) {
8322 vector<vector<bool>> next = board;
8323 next[line][i] = true;
8324 dfs(next, line + 1, n, ans);
8325 }
8326 }
8327 }
8328
8329 bool Solution::valid(const vector<vector<bool>> &board, int n, int x, int y) {
8330 for(int i = 0; i < x; i++) {
8331 if(board[i][y]) {
8332 return false;
8333 }
8334 }
8335 for(int i = x, j = y; i >= 0 && i < n && j >= 0 && j < n; i--, j--) {
8336 if(board[i][j]) {
8337 return false;
8338 }
8339 }
8340 for(int i = x, j = y; i >= 0 && i < n && j >= 0 && j < n; i--, j++) {
8341 if(board[i][j]) {
8342 return false;
8343 }
8344 }
8345 return true;
8346 }
8347
8348 vector<string> Solution::toStringVec(const vector<vector<bool>> &board) {
8349 vector<string> ans(board.size());
8350 for(int i = 0; i < board.size(); i++) {
8351 ostringstream oss;
8352 for(int j = 0; j < board[i].size(); j++) {
8353 oss << (board[i][j] ? 'Q' : '.');
8354 }
8355 ans[i] = oss.str();
8356 }
8357 return ans;
8358 }
8359 }// namespace n_queens
8360
8361 namespace sudoku_solver {
8362 void Solution::solveSudoku(vector<vector<char>> &board) { dfs(board, board); }
8363
8364 bool Solution::dfs(const vector<vector<char>> &board, vector<vector<char>> &ans) {
8365 for(int i = 0; i < 9; i++) {
8366 for(int j = 0; j < 9; j++) {
8367 if(board[i][j] == '.') {
8368 for(char c = '1'; c <= '9'; c++) {
8369 if(valid(board, i, j, c)) {
8370 bool haveValid = true;
8371 vector<vector<char>> next = board;
8372 next[i][j] = c;
8373 if(dfs(next, ans)) {
8374 return true;
8375 }
8376 }
8377 }
8378 return false;
8379 }
8380 }
8381 }
8382 ans = board;
8383 return true;
8384 }
8385
8386 bool Solution::valid(const vector<vector<char>> &board, int x, int y, char num) {
8387 for(int i = 0; i < 9; i++) {
8388 if(board[i][y] == num) {
8389 return false;
8390 }
8391 }
8392 for(int j = 0; j < 9; j++) {
8393 if(board[x][j] == num) {
8394 return false;
8395 }
8396 }
8397 for(int i = 0; i < 3; i++) {
8398 for(int j = 0; j < 3; j++) {
8399 if(board[x / 3 * 3 + i][y / 3 * 3 + j] == num) {
8400 return false;
8401 }
8402 }
8403 }
8404 return true;
8405 }
8406 }// namespace sudoku_solver
8407
8408 namespace regular_expression_matching {
8409 bool Solution::isMatch(const string &s, const string &p) { return dfs(s, p, 0, 0); }
8410
8411 bool Solution::dfs(const string &s, const string &p, int si, int pi) {
8412 if(pi == p.length() && si == s.length()) {
8413 return true;
8414 }
8415 if(pi == p.length()) {
8416 return false;
8417 }
8418 const char c = p[pi++];
8419 bool multiple = false;
8420 if(pi < p.length() && p[pi] == '*') {
8421 multiple = true;
8422 pi++;
8423 }
8424 if(!multiple) {
8425 if(si == s.length()) {
8426 return false;
8427 }
8428 if(c == '.' || s[si] == c) {
8429 return dfs(s, p, si + 1, pi);
8430 }
8431 return false;
8432 }
8433 if(c == '.') {
8434 for(int i = si; i <= s.length(); i++) {
8435 if(dfs(s, p, i, pi)) {
8436 return true;
8437 }
8438 }
8439 return false;
8440 }
8441 int i = si;
8442 while(s[i] == c) {
8443 if(dfs(s, p, ++i, pi)) {
8444 return true;
8445 }
8446 }
8447 return dfs(s, p, si, pi);
8448 }
8449 }// namespace regular_expression_matching
8450
8451 namespace different_ways_to_add_parentheses {
8452 vector<int> Solution::eval(const string &expr, int start, int end) {
8453 vector<int> ans;
8454 bool allDigit = true;
8455 for(int i = start; i <= end; i++) {
8456 if(!isdigit(expr[i])) {
8457 allDigit = false;
8458 vector left = eval(expr, start, i - 1);
8459 vector right = eval(expr, i + 1, end);
8460 for(const auto &l: left) {
8461 for(const auto &r: right) {
8462 switch(expr[i]) {
8463 case '+':
8464 ans.emplace_back(l + r);
8465 break;
8466 case '-':
8467 ans.emplace_back(l - r);
8468 break;
8469 case '*':
8470 ans.emplace_back(l * r);
8471 break;
8472 }
8473 }
8474 }
8475 }
8476 }
8477 if(allDigit) {
8478 int val = 0;
8479 for(int i = start; i <= end; i++) {
8480 val *= 10;
8481 val += expr[i] - '0';
8482 }
8483 ans.emplace_back(val);
8484 }
8485 return ans;
8486 }
8487
8488 vector<int> Solution::diffWaysToCompute(const string &expression) {
8489 vector ans = eval(expression, 0, expression.length() - 1);
8490 sort(ans.begin(), ans.end());
8491 return ans;
8492 }
8493 }// namespace different_ways_to_add_parentheses
8494
8495 namespace remove_invalid_parentheses {
8496 vector<string> Solution::removeInvalidParentheses(const string &s) {
8497 vector<string> ans;
8498 unordered_set<string> currSet;
8499
8500 currSet.insert(s);
8501 while(true) {
8502 for(auto &str: currSet) {
8503 if(isValid(str))
8504 ans.emplace_back(str);
8505 }
8506 if(!ans.empty()) {
8507 sort(ans.begin(), ans.end());
8508 return ans;
8509 }
8510 unordered_set<string> nextSet;
8511 for(auto &str: currSet) {
8512 for(int i = 0; i < str.size(); i++) {
8513 if(i > 0 && str[i] == str[i - 1]) {
8514 continue;
8515 }
8516 if(str[i] == '(' || str[i] == ')') {
8517 nextSet.insert(str.substr(0, i) + str.substr(i + 1, str.size()));
8518 }
8519 }
8520 }
8521 currSet = nextSet;
8522 }
8523 }
8524
8525 bool Solution::isValid(const string &str) {
8526 int count = 0;
8527
8528 for(const char c: str) {
8529 if(c == '(') {
8530 count++;
8531 } else if(c == ')') {
8532 count--;
8533 if(count < 0) {
8534 return false;
8535 }
8536 }
8537 }
8538
8539 return count == 0;
8540 }
8541 }// namespace remove_invalid_parentheses
8542
8543 namespace median_of_two_sorted_arrays {
8544 double Solution::findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {
8545 if(nums1.size() > nums2.size()) {
8546 return findMedianSortedArrays(nums2, nums1);
8547 }
8548
8549 const int m = nums1.size();
8550 const int n = nums2.size();
8551 int left = 0, right = m;
8552 // median1:前一部分的最大值
8553 // median2:后一部分的最小值
8554 int median1 = 0, median2 = 0;
8555
8556 while(left <= right) {
8557 // 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
8558 // 后一部分包含 nums1[i .. m-1] 和 nums2[j .. n-1]
8559 const int i = (left + right) / 2;
8560 const int j = (m + n + 1) / 2 - i;
8561
8562 // nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
8563 int nums_im1 = i == 0 ? INT_MIN : nums1[i - 1];
8564 int nums_i = i == m ? INT_MAX : nums1[i];
8565 int nums_jm1 = j == 0 ? INT_MIN : nums2[j - 1];
8566 int nums_j = j == n ? INT_MAX : nums2[j];
8567
8568 if(nums_im1 <= nums_j) {
8569 median1 = max(nums_im1, nums_jm1);
8570 median2 = min(nums_i, nums_j);
8571 left = i + 1;
8572 } else {
8573 right = i - 1;
8574 }
8575 }
8576
8577 return (m + n) % 2 == 0 ? (median1 + median2) / 2.0 : median1;
8578 }
8579 }// namespace median_of_two_sorted_arrays
8580
8581 namespace count_of_smaller_numbers_after_self {
8582 vector<int> Solution::countSmaller(vector<int> &nums) {
8583 vector<int> resultList;
8584
8585 Discretization(nums);
8586
8587 Init(nums.size() + 5);
8588
8589 for(int i = static_cast<int>(nums.size()) - 1; i >= 0; --i) {
8590 const int id = getId(nums[i]);
8591 resultList.push_back(Query(id - 1));
8592 Update(id);
8593 }
8594
8595 reverse(resultList.begin(), resultList.end());
8596
8597 return resultList;
8598 }
8599
8600 void Solution::Init(int length) { c.resize(length, 0); }
8601
8602 int Solution::LowBit(int x) { return x & -x; }
8603
8604 void Solution::Update(int pos) {
8605 while(pos < c.size()) {
8606 c[pos] += 1;
8607 pos += LowBit(pos);
8608 }
8609 }
8610
8611 int Solution::Query(int pos) const {
8612 int ret = 0;
8613
8614 while(pos > 0) {
8615 ret += c[pos];
8616 pos -= LowBit(pos);
8617 }
8618
8619 return ret;
8620 }
8621
8622 void Solution::Discretization(vector<int> &nums) {
8623 a.assign(nums.begin(), nums.end());
8624 sort(a.begin(), a.end());
8625 a.erase(unique(a.begin(), a.end()), a.end());
8626 }
8627
8628 int Solution::getId(int x) { return lower_bound(a.begin(), a.end(), x) - a.begin() + 1; }
8629 }// namespace count_of_smaller_numbers_after_self
8630
8631 namespace best_time_to_buy_and_sell_stock_with_cooldown {
8632 int Solution::maxProfit(vector<int> &prices) {
8633 if(prices.empty()) {
8634 return 0;
8635 }
8636
8637 const int n = prices.size();
8638 int f0 = -prices[0];
8639 int f1 = 0;
8640 int f2 = 0;
8641 for(int i = 1; i < n; ++i) {
8642 tie(f0, f1, f2) = make_tuple(max(f0, f2 - prices[i]), f0 + prices[i], max(f1, f2));
8643 }
8644
8645 return max(f1, f2);
8646 }
8647 }// namespace best_time_to_buy_and_sell_stock_with_cooldown
8648
8649 namespace best_time_to_buy_and_sell_stock_with_transaction_fee {
8650 int Solution::maxProfit(vector<int> &prices, int fee) {
8651 const int n = prices.size();
8652 vector<int> holding(n);
8653 vector<int> not_holding(n);
8654 not_holding[0] = 0;
8655 holding[0] = -prices[0];
8656 for(int i = 1; i < n; i++) {
8657 not_holding[i] = max(not_holding[i - 1], holding[i - 1] + prices[i] - fee);
8658 holding[i] = max(holding[i - 1], not_holding[i - 1] - prices[i]);
8659 }
8660 return max(not_holding.back(), holding.back());
8661 }
8662 }// namespace best_time_to_buy_and_sell_stock_with_transaction_fee
8663
8664 namespace split_array_largest_sum {
8665 int Solution::splitArray(vector<int> &nums, int m) {
8666 int l = 0;
8667 int r = 0;
8668 for(auto num: nums) {
8669 r += num;
8670 l = max(l, num);
8671 }
8672 while(l < r) {
8673 const int mid = (l + r) / 2;
8674 const int cnt = get_m(nums, mid);
8675 if(cnt == m) {
8676 r = mid;
8677 } else if(cnt > m) {
8678 l = mid + 1;
8679 } else if(cnt < m) {
8680 r = mid - 1;
8681 }
8682 }
8683 return l;
8684 }
8685
8686 int Solution::get_m(const vector<int> &nums, int msum) {
8687 int ans = 0;
8688 int c = 0;
8689 for(const auto num: nums) {
8690 if(c + num > msum) {
8691 ans++;
8692 c = 0;
8693 }
8694 c += num;
8695 }
8696 if(c > 0) {
8697 ans++;
8698 }
8699 return ans;
8700 }
8701 }// namespace split_array_largest_sum
8702
8703 namespace house_robber_iii {
8705 int ans = 0;
8706 return max(dfs(true, root), dfs(false, root));
8707 }
8708
8709 int Solution::dfs(bool steal, TreeNode *node) {
8710 if(um.contains({node, steal})) {
8711 return um[{node, steal}];
8712 }
8713 int ans = steal ? node->val : 0;
8714 if(node->left != nullptr) {
8715 const int ns = dfs(!steal, node->left);
8716 const int s = !steal ? dfs(steal, node->left) : 0;
8717 ans += max(s, ns);
8718 }
8719 if(node->right != nullptr) {
8720 const int ns = dfs(!steal, node->right);
8721 const int s = !steal ? dfs(steal, node->right) : 0;
8722 ans += max(s, ns);
8723 }
8724 um[{node, steal}] = ans;
8725 return ans;
8726 }
8727
8728 size_t myhash::operator()(const pair<TreeNode *, bool> &p) const { return (uint64_t) p.first * 2 + (p.second ? 1 : 0); }
8729
8730 bool myeq::operator()(const pair<TreeNode *, bool> &p1, const pair<TreeNode *, bool> &p2) const { return p1.first == p2.first && p1.second == p2.second; }
8731 }// namespace house_robber_iii
8732
8733 namespace maximal_square {
8734 int Solution::maximalSquare(vector<vector<char>> &matrix) {
8735 const int m = matrix.size();
8736 const int n = matrix[0].size();
8737 vector horizontal_next_1s(m, vector(n, 0));
8738 vector vertical_next_1s(m, vector(n, 0));
8739 vector dp(m + 1, vector(n + 1, 0));
8740 for(int i = 0; i < m; i++) {
8741 int cnt = 0;
8742 for(int j = n - 1; j >= 0; j--) {
8743 if(matrix[i][j] == '1') {
8744 cnt++;
8745 } else {
8746 cnt = 0;
8747 }
8748 horizontal_next_1s[i][j] = cnt;
8749 }
8750 }
8751 for(int j = 0; j < n; j++) {
8752 int cnt = 0;
8753 for(int i = m - 1; i >= 0; i--) {
8754 if(matrix[i][j] == '1') {
8755 cnt++;
8756 } else {
8757 cnt = 0;
8758 }
8759 vertical_next_1s[i][j] = cnt;
8760 }
8761 }
8762 int ans = 0;
8763 for(int i = m - 1; i >= 0; i--) {
8764 for(int j = n - 1; j >= 0; j--) {
8765 if(matrix[i][j] == '1') {
8766 dp[i][j] = min(min(vertical_next_1s[i][j], horizontal_next_1s[i][j]), 1 + dp[i + 1][j + 1]);
8767 ans = max(ans, dp[i][j]);
8768 }
8769 }
8770 }
8771 return ans * ans;
8772 }
8773 }// namespace maximal_square
8774
8775 namespace maximal_rectangle {
8776 int Solution::maximalRectangle(vector<vector<char>> &matrix) {
8777 const int m = matrix.size();
8778 if(m == 0) {
8779 return 0;
8780 }
8781 const int n = matrix[0].size();
8782 vector left(m, vector(n, 0));
8783
8784 for(int i = 0; i < m; i++) {
8785 for(int j = 0; j < n; j++) {
8786 if(matrix[i][j] == '1') {
8787 left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
8788 }
8789 }
8790 }
8791
8792 int ret = 0;
8793 for(int j = 0; j < n; j++) {
8794 // 对于每一列,使用基于柱状图的方法
8795 vector<int> up(m, 0), down(m, 0);
8796
8797 stack<int> stk;
8798 for(int i = 0; i < m; i++) {
8799 while(!stk.empty() && left[stk.top()][j] >= left[i][j]) {
8800 stk.pop();
8801 }
8802 up[i] = stk.empty() ? -1 : stk.top();
8803 stk.push(i);
8804 }
8805 stk = stack<int>();
8806 for(int i = m - 1; i >= 0; i--) {
8807 while(!stk.empty() && left[stk.top()][j] >= left[i][j]) {
8808 stk.pop();
8809 }
8810 down[i] = stk.empty() ? m : stk.top();
8811 stk.push(i);
8812 }
8813
8814 for(int i = 0; i < m; i++) {
8815 const int height = down[i] - up[i] - 1;
8816 int area = height * left[i][j];
8817 ret = max(ret, area);
8818 }
8819 }
8820 return ret;
8821 }
8822 }// namespace maximal_rectangle
8823
8824 namespace predict_the_winner {
8825 bool Solution::PredictTheWinner(vector<int> &nums) {
8826 const int length = nums.size();
8827 auto dp = vector<int>(length);
8828 for(int i = 0; i < length; i++) {
8829 dp[i] = nums[i];
8830 }
8831 for(int i = length - 2; i >= 0; i--) {
8832 for(int j = i + 1; j < length; j++) {
8833 dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]);
8834 }
8835 }
8836 return dp[length - 1] >= 0;
8837 }
8838 }// namespace predict_the_winner
8839
8840 namespace palindrome_partitioning {
8841
8842 vector<vector<string>> Solution::partition(const string &s) {
8843 const vector<string> vec;
8844 vector<vector<string>> ans;
8845 dfs(vec, s, ans, 0, 0);
8846 return ans;
8847 }
8848
8849 bool Solution::is_palindromic(const string &s, int start, int end) {
8850 for(int i = start, j = end; i < j; i++, j--) {
8851 if(s[i] != s[j]) {
8852 return false;
8853 }
8854 }
8855 return true;
8856 }
8857
8858 void Solution::dfs(const vector<string> &current, const string &s, vector<vector<string>> &ans, int start, int cursor) {
8859 if(cursor == s.length() - 1 && is_palindromic(s, start, cursor)) {
8860 ans.emplace_back(current);
8861 ans.back().emplace_back(s.substr(start, cursor - start + 1));
8862 return;
8863 }
8864 if(cursor >= s.length() - 1 || start >= s.length()) {
8865 return;
8866 }
8867 if(is_palindromic(s, start, cursor)) {
8868 vector next = current;
8869 next.emplace_back(s.substr(start, cursor - start + 1));
8870 dfs(next, s, ans, cursor + 1, cursor + 1);
8871 }
8872 dfs(current, s, ans, start, cursor + 1);
8873 }
8874 }// namespace palindrome_partitioning
8875
8876 namespace palindrome_partitioning_ii {
8877 int Solution::minCut(string s) {
8878 vector is_palindromic(s.length(), vector(s.length(), false));
8879 for(int i = 0; i < s.length(); i++) {
8880 for(int j = 0; i - j >= 0 && i + j < s.length() && s[i - j] == s[i + j]; j++) {
8881 is_palindromic[i - j][i + j] = true;
8882 }
8883 }
8884 for(int i = 0; i < s.length() - 1; i++) {
8885 if(s[i] == s[i + 1]) {
8886 for(int j = 0; i - j >= 0 && i + 1 + j < s.length() && s[i - j] == s[i + 1 + j]; j++) {
8887 is_palindromic[i - j][i + 1 + j] = true;
8888 }
8889 }
8890 }
8891 vector dp(s.length(), 2000);
8892 dp[0] = 0;
8893 for(int j = 1; j < dp.size(); j++) {
8894 if(is_palindromic[0][j]) {
8895 dp[j] = 0;
8896 continue;
8897 }
8898 for(int i = j; i >= 0; i--) {
8899 if(is_palindromic[i][j]) {
8900 dp[j] = min(dp[j], dp[i - 1] + 1);
8901 }
8902 }
8903 }
8904 return dp.back();
8905 }
8906 }// namespace palindrome_partitioning_ii
8907
8908 namespace partition_equal_subset_sum {
8909 bool Solution::canPartition(vector<int> &nums) {
8910 const int n = nums.size();
8911 if(n < 2) {
8912 return false;
8913 }
8914 const int sum = accumulate(nums.begin(), nums.end(), 0);
8915 const int maxNum = *max_element(nums.begin(), nums.end());
8916 if(sum & 1) {
8917 return false;
8918 }
8919 const int target = sum / 2;
8920 if(maxNum > target) {
8921 return false;
8922 }
8923 vector dp(n, vector(target + 1, 0));
8924 for(int i = 0; i < n; i++) {
8925 dp[i][0] = true;
8926 }
8927 dp[0][nums[0]] = true;
8928 for(int i = 1; i < n; i++) {
8929 const int num = nums[i];
8930 for(int j = 1; j <= target; j++) {
8931 if(j >= num) {
8932 dp[i][j] = dp[i - 1][j] | dp[i - 1][j - num];
8933 } else {
8934 dp[i][j] = dp[i - 1][j];
8935 }
8936 }
8937 }
8938 return dp[n - 1][target];
8939 }
8940 }// namespace partition_equal_subset_sum
8941
8942 namespace minimum_cost_for_tickets {
8943 int Solution::mincostTickets(vector<int> &days, vector<int> &costs) {
8944 unordered_set<int> us;
8945 int end = 0;
8946 for(const auto &day: days) {
8947 us.insert(day);
8948 end = max(end, day);
8949 }
8950 vector dp(end + 1, 0);
8951 for(int i = 1; i <= end; i++) {
8952 dp[i] = i - 1 >= 0 ? dp[i - 1] : 0;
8953 if(us.contains(i)) {
8954 dp[i] += costs[0];
8955 dp[i] = min(dp[i], (i - 7 >= 0 ? dp[i - 7] : 0) + costs[1]);
8956 dp[i] = min(dp[i], (i - 30 >= 0 ? dp[i - 30] : 0) + costs[2]);
8957 }
8958 }
8959 return dp.back();
8960 }
8961 }// namespace minimum_cost_for_tickets
8962
8963 namespace best_time_to_buy_and_sell_stock_iii {
8964 int Solution::maxProfit(vector<int> &prices) {
8965 vector dp(5, vector<long>(prices.size(), -10000000000));
8966 // 0 - 不持有
8967 // 1 - 第一次持有
8968 // 2 - 第一次卖出
8969 // 3 - 第二次持有
8970 // 4 - 第二次卖出
8971 dp[0][0] = 0;
8972 dp[1][0] = -prices[0];
8973 for(int i = 1; i < prices.size(); i++) {
8974 dp[0][i] = dp[0][i - 1];
8975 dp[1][i] = max(dp[1][i - 1], dp[0][i - 1] - prices[i]);
8976 dp[2][i] = max(dp[2][i - 1], dp[1][i - 1] + prices[i]);
8977 dp[3][i] = max(dp[3][i - 1], dp[2][i - 1] - prices[i]);
8978 dp[4][i] = max(dp[4][i - 1], dp[3][i - 1] + prices[i]);
8979 }
8980 long ans = dp[0].back();
8981 for(int i = 1; i <= 4; i++) {
8982 ans = max(ans, dp[i].back());
8983 }
8984 return ans;
8985 }
8986 }// namespace best_time_to_buy_and_sell_stock_iii
8987
8988 namespace dungeon_game {
8989 int Solution::calculateMinimumHP(vector<vector<int>> &dungeon) {
8990 const int n = dungeon.size(), m = dungeon[0].size();
8991 vector dp(n + 1, vector(m + 1, INT_MAX));
8992 dp[n][m - 1] = dp[n - 1][m] = 1;
8993 for(int i = n - 1; i >= 0; --i) {
8994 for(int j = m - 1; j >= 0; --j) {
8995 const int minn = min(dp[i + 1][j], dp[i][j + 1]);
8996 dp[i][j] = max(minn - dungeon[i][j], 1);
8997 }
8998 }
8999 return dp[0][0];
9000 }
9001 }// namespace dungeon_game
9002
9003 namespace course_schedule {
9004 bool Solution::canFinish(int numCourses, vector<vector<int>> &prerequisites) {
9005 vector<int> in(numCourses);
9006 vector<unordered_set<int>> out(numCourses);
9007 unordered_set<int> learned;
9008 for(auto &prerequisite: prerequisites) {
9009 in[prerequisite[1]]++;
9010 out[prerequisite[0]].insert(prerequisite[1]);
9011 }
9012 bool hasChange = true;
9013 while(hasChange) {
9014 hasChange = false;
9015 for(int i = 0; i < numCourses; i++) {
9016 if(in[i] == 0 && !learned.contains(i)) {
9017 hasChange = true;
9018 learned.insert(i);
9019 for(auto &next: out[i]) {
9020 in[next]--;
9021 }
9022 }
9023 }
9024 }
9025 for(int i = 0; i < numCourses; i++) {
9026 if(in[i] != 0) {
9027 return false;
9028 }
9029 }
9030 return true;
9031 }
9032 }// namespace course_schedule
9033
9034 namespace course_schedule_ii {
9035 vector<int> Solution::findOrder(int numCourses, vector<vector<int>> &prerequisites) {
9036 vector<int> ans;
9037 vector<int> in(numCourses);
9038 vector<unordered_set<int>> out(numCourses);
9039 unordered_set<int> learned;
9040 for(auto &prerequisite: prerequisites) {
9041 in[prerequisite[0]]++;
9042 out[prerequisite[1]].insert(prerequisite[0]);
9043 }
9044 bool hasChange = true;
9045 while(hasChange) {
9046 hasChange = false;
9047 for(int i = 0; i < numCourses; i++) {
9048 if(in[i] == 0 && !learned.contains(i)) {
9049 hasChange = true;
9050 learned.insert(i);
9051 ans.emplace_back(i);
9052 for(auto &next: out[i]) {
9053 in[next]--;
9054 }
9055 }
9056 }
9057 }
9058 if(ans.size() == numCourses) {
9059 return ans;
9060 }
9061 return {};
9062 }
9063 }// namespace course_schedule_ii
9064
9065 namespace longest_increasing_path_in_a_matrix {
9066 int Solution::longestIncreasingPath(vector<vector<int>> &matrix) {
9067 if(matrix.empty() || matrix[0].empty()) {
9068 return 0;
9069 }
9070 rows = matrix.size();
9071 columns = matrix[0].size();
9072 auto outdegrees = vector(rows, vector<int>(columns));
9073 for(int i = 0; i < rows; ++i) {
9074 for(int j = 0; j < columns; ++j) {
9075 for(int k = 0; k < 4; ++k) {
9076 const int newRow = i + dirs[k][0], newColumn = j + dirs[k][1];
9077 if(newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[i][j]) {
9078 ++outdegrees[i][j];
9079 }
9080 }
9081 }
9082 }
9083 queue<pair<int, int>> q;
9084 for(int i = 0; i < rows; ++i) {
9085 for(int j = 0; j < columns; ++j) {
9086 if(outdegrees[i][j] == 0) {
9087 q.push({i, j});
9088 }
9089 }
9090 }
9091 int ans = 0;
9092 while(!q.empty()) {
9093 ++ans;
9094 const int size = q.size();
9095 for(int i = 0; i < size; ++i) {
9096 const auto cell = q.front();
9097 q.pop();
9098 const int row = cell.first, column = cell.second;
9099 for(int k = 0; k < 4; ++k) {
9100 int newRow = row + dirs[k][0], newColumn = column + dirs[k][1];
9101 if(newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] < matrix[row][column]) {
9102 --outdegrees[newRow][newColumn];
9103 if(outdegrees[newRow][newColumn] == 0) {
9104 q.push({newRow, newColumn});
9105 }
9106 }
9107 }
9108 }
9109 }
9110 return ans;
9111 }
9112 }// namespace longest_increasing_path_in_a_matrix
9113
9114 namespace parallel_courses {
9115 int Solution::minimumSemesters(int n, vector<vector<int>> &relations) {
9116 vector<node *> nodes(n);
9117 for(int i = 1; i <= n; i++) {
9118 nodes[i - 1] = new node(i, 0);
9119 }
9120 for(const auto &relation: relations) {
9121 nodes[relation[1] - 1]->pred.insert(nodes[relation[0] - 1]);
9122 nodes[relation[0] - 1]->out++;
9123 }
9124 bool flag = true;
9125 unordered_set<int> vis;
9126 while(flag) {
9127 flag = false;
9128 for(int i = 0; i < n; i++) {
9129 if(nodes[i]->out == 0) {
9130 if(vis.contains(i)) {
9131 continue;
9132 }
9133 vis.insert(i);
9134 flag = true;
9135 for(node *next: nodes[i]->pred) {
9136 next->out--;
9137 next->len = max(next->len, nodes[i]->len + 1);
9138 }
9139 }
9140 }
9141 }
9142 int ans = 0;
9143 for(int i = 0; i < n; i++) {
9144 if(nodes[i]->out != 0) {
9145 return -1;
9146 }
9147 ans = max(ans, nodes[i]->len);
9148 }
9149 return ans;
9150 }
9151 }// namespace parallel_courses
9152
9153 namespace alien_dictionary {
9154 string Solution::alienOrder(vector<string> &words) {
9155 unordered_map<char, unordered_set<char>> g;
9156 unordered_map<char, int> in;
9157 ostringstream oss;
9158 unordered_set<char> charset;
9159 for(const auto &word: words) {
9160 for(const auto &ch: word) {
9161 charset.insert(ch);
9162 }
9163 }
9164 for(const auto &ch: charset) {
9165 g[ch] = unordered_set<char>();
9166 in[ch] = 0;
9167 }
9168 int max_len = 0;
9169 for(const auto &word: words) {
9170 max_len = max(max_len, static_cast<int>(word.length()));
9171 }
9172 for(int i = 0; i < max_len; i++) {
9173 unordered_map<string, vector<string>> um;
9174 for(const auto &word: words) {
9175 if(word.length() >= i) {
9176 um[i > 0 ? word.substr(0, i) : ""].emplace_back(word);
9177 }
9178 }
9179 for(const auto &[pred, section]: um) {
9180 for(int j = 0, k = 1; k < section.size(); j++, k++) {
9181 if(i < section[j].length() && i < section[k].length()) {
9182 if(section[j][i] != section[k][i]) {
9183 g[section[j][i]].insert(section[k][i]);
9184 }
9185 } else if(i < section[j].length()) {
9186 return "";
9187 }
9188 }
9189 }
9190 }
9191 for(const auto &[k, section]: g) {
9192 for(const auto &n: section) {
9193 in[n]++;
9194 }
9195 }
9196 bool flag = true;
9197 unordered_set<char> vis;
9198 while(flag) {
9199 flag = false;
9200 for(const auto &[ch, n]: in) {
9201 if(n == 0 && !vis.contains(ch)) {
9202 flag = true;
9203 vis.insert(ch);
9204 oss << ch;
9205 for(const auto &nc: g[ch]) {
9206 in[nc]--;
9207 }
9208 }
9209 }
9210 }
9211 for(const auto &[ch, n]: in) {
9212 if(n != 0) {
9213 return "";
9214 }
9215 }
9216 return oss.str();
9217 }
9218 }// namespace alien_dictionary
9219
9220 namespace single_number_iii {
9221 vector<int> Solution::singleNumber(vector<int> &nums) {
9222 int xorsum = 0;
9223 for(const int num: nums) {
9224 xorsum ^= num;
9225 }
9226 // 防止溢出
9227 const int lsb = xorsum == INT_MIN ? xorsum : xorsum & -xorsum;
9228 int type1 = 0, type2 = 0;
9229 for(const int num: nums) {
9230 if(num & lsb) {
9231 type1 ^= num;
9232 } else {
9233 type2 ^= num;
9234 }
9235 }
9236 return {type1, type2};
9237 }
9238 }// namespace single_number_iii
9239
9240 namespace shortest_path_to_get_all_keys {
9241 int Solution::shortestPathAllKeys(vector<string> &grid) {
9242 priority_queue<frame> pq;
9243 int m = grid.size();
9244 int n = grid[0].size();
9245 int start_x = 0;
9246 int start_y = 0;
9247 int lock_cnt = 0;
9248 unordered_map<unsigned, vector<vector<int>>> min_step;
9249 for(int i = 0; i < m; i++) {
9250 for(int j = 0; j < n; j++) {
9251 if(grid[i][j] == START) {
9252 start_x = i;
9253 start_y = j;
9254 } else if(isupper(grid[i][j])) {
9255 lock_cnt++;
9256 }
9257 }
9258 }
9259 frame start(start_x, start_y, lock_cnt);
9260 pq.push(start);
9261 while(!pq.empty()) {
9262 frame f = pq.top();
9263 pq.pop();
9264 if(f.keys.size() == lock_cnt) {
9265 return f.step;
9266 }
9267 if(!min_step.contains(f.get_mask())) {
9268 min_step[f.get_mask()] = vector(m, vector(n, INT_MAX));
9269 }
9270 if(min_step[f.get_mask()][f.x][f.y] <= f.step) {
9271 continue;
9272 }
9273 min_step[f.get_mask()][f.x][f.y] = f.step;
9274 const pair<int, int> nexts[4] = {{f.x + 1, f.y}, {f.x - 1, f.y}, {f.x, f.y + 1}, {f.x, f.y - 1}};
9275 for(const auto &[n_x, n_y]: nexts) {
9276 if(n_x >= 0 && n_x < m && n_y >= 0 && n_y < n && grid[n_x][n_y] != WALL) {
9277 if(islower(grid[n_x][n_y])) {
9278 frame next = f;
9279 next.x = n_x;
9280 next.y = n_y;
9281 next.step++;
9282 next.keys.insert(grid[n_x][n_y]);
9283 if(!min_step.contains(next.get_mask())) {
9284 min_step[next.get_mask()] = vector(m, vector(n, INT_MAX));
9285 }
9286 if(min_step[next.get_mask()][n_x][n_y] > next.step) {
9287 pq.push(next);
9288 }
9289 } else if(isupper(grid[n_x][n_y])) {
9290 if(f.keys.contains(static_cast<char>(tolower(grid[n_x][n_y])))) {
9291 frame next = f;
9292 next.x = n_x;
9293 next.y = n_y;
9294 next.step++;
9295 if(!min_step.contains(next.get_mask())) {
9296 min_step[next.get_mask()] = vector(m, vector(n, INT_MAX));
9297 }
9298 if(min_step[next.get_mask()][n_x][n_y] > next.step) {
9299 pq.push(next);
9300 }
9301 }
9302 } else {
9303 frame next = f;
9304 next.x = n_x;
9305 next.y = n_y;
9306 next.step++;
9307 if(!min_step.contains(next.get_mask())) {
9308 min_step[next.get_mask()] = vector(m, vector(n, INT_MAX));
9309 }
9310 if(min_step[next.get_mask()][n_x][n_y] > next.step) {
9311 pq.push(next);
9312 }
9313 }
9314 }
9315 }
9316 }
9317 return -1;
9318 }
9319
9320 bool frame::operator<(const frame &f) const {
9321 if(step != f.step) {
9322 return step > f.step;
9323 }
9324 return keys.size() < f.keys.size();
9325 }
9326
9327 unsigned frame::get_mask() const {
9328 unsigned mask = 0;
9329 for(const auto &key: keys) {
9330 mask |= 1 << key - 'a';
9331 }
9332 return mask;
9333 }
9334 }// namespace shortest_path_to_get_all_keys
9335
9336 namespace minimum_number_of_k_consecutive_bit_flips {
9337 int Solution::minKBitFlips(vector<int> &nums, int k) {
9338 const int n = nums.size();
9339 int ans = 0, revCnt = 0;
9340 for(int i = 0; i < n; ++i) {
9341 if(i >= k && nums[i - k] > 1) {
9342 revCnt ^= 1;
9343 nums[i - k] -= 2;// 复原数组元素,若允许修改数组 nums,则可以省略
9344 }
9345 if(nums[i] == revCnt) {
9346 if(i + k > n) {
9347 return -1;
9348 }
9349 ++ans;
9350 revCnt ^= 1;
9351 nums[i] += 2;
9352 }
9353 }
9354 return ans;
9355 }
9356 }// namespace minimum_number_of_k_consecutive_bit_flips
9357
9358 namespace design_underground_system {
9359 void UndergroundSystem::checkIn(int id, const string &stationName, int t) { records[id] = {stationName, t}; }
9360 void UndergroundSystem::checkOut(int id, const string &stationName, int t) { um[records[id].first][stationName].emplace_back(t - records[id].second); }
9361
9362 double UndergroundSystem::getAverageTime(const string &startStation, const string &endStation) {
9363 int total = 0;
9364 for(const auto t: um[startStation][endStation]) {
9365 total += t;
9366 }
9367 return static_cast<double>(total) / um[startStation][endStation].size();
9368 }
9369 }// namespace design_underground_system
9370
9371 namespace lru_cache {
9373 : capacity(capacity) {}
9374
9375 int LRUCache::get(int key) {
9376 if(um.contains(key)) {
9377 if(key != keys.back()) {
9378 keys.erase(find(keys.begin(), keys.end(), key));
9379 keys.emplace_back(key);
9380 }
9381 return um[key];
9382 }
9383 return -1;
9384 }
9385
9386 void LRUCache::put(int key, int value) {
9387 if(um.size() == capacity) {
9388 if(um.contains(key)) {
9389 //满 含
9390 if(key != keys.back()) {
9391 keys.erase(find(keys.begin(), keys.end(), key));
9392 keys.emplace_back(key);
9393 }
9394 } else {
9395 //满 不含
9396 um.erase(*keys.begin());
9397 keys.erase(keys.begin());
9398 keys.emplace_back(key);
9399 }
9400 } else {
9401 if(um.contains(key)) {
9402 //未满 含
9403 if(key != keys.back()) {
9404 keys.erase(find(keys.begin(), keys.end(), key));
9405 keys.emplace_back(key);
9406 }
9407 } else {
9408 //未满 不含
9409 keys.emplace_back(key);
9410 }
9411 }
9412 um[key] = value;
9413 }
9414 }// namespace lru_cache
9415
9416 namespace time_based_key_value_store {
9417 void TimeMap::set(const string &key, string value, int timestamp) { um[key][timestamp] = std::move(value); }
9418
9419 string TimeMap::get(const string &key, int timestamp) {
9420 const auto it = um[key].lower_bound(timestamp);
9421 return it == um[key].end() ? "" : it->second;
9422 }
9423 }// namespace time_based_key_value_store
9424
9425 namespace range_module {
9426 void RangeModule::addRange(int left, int right) { tree.assign(left, right - 1, true); }
9427
9428 bool RangeModule::queryRange(int left, int right) { return tree.check(left, right - 1); }
9429
9431 }// namespace range_module
9432
9433 namespace lfu_cache {
9434 int LFUCache::get(int key) {
9435 if(capacity == 0) {
9436 return -1;
9437 }
9438 int ans = -1;
9439 if(um.contains(key)) {
9440 // 如果存在
9441 ans = um[key];
9442 cnt[key]++; //增加计数
9443 const auto it = find(tnc[cnt[key] - 1].begin(), tnc[cnt[key] - 1].end(), key);//
9444 if(it != tnc[cnt[key] - 1].end()) {
9445 tnc[cnt[key] - 1].erase(it);
9446 if(tnc[cnt[key] - 1].empty()) {
9447 tnc.erase(cnt[key] - 1);
9448 }
9449 }
9450 tnc[cnt[key]].emplace_back(key);
9451 }
9452 return ans;
9453 }
9454
9455 void LFUCache::put(int key, int value) {
9456 if(capacity == 0) {
9457 return;
9458 }
9459 cnt[key]++;
9460 if(um.size() == capacity) {
9461 //满
9462 if(um.contains(key)) {
9463 //已存在
9464 tnc[cnt[key] - 1].erase(find(tnc[cnt[key] - 1].begin(), tnc[cnt[key] - 1].end(), key));
9465 if(tnc[cnt[key] - 1].empty()) {
9466 tnc.erase(cnt[key] - 1);
9467 }
9468 } else {
9469 //不存在
9470 while(tnc.begin()->second.empty()) {
9471 tnc.erase(tnc.begin());
9472 }
9473 const auto evicted = tnc.begin()->second.begin();
9474 const int val = *evicted;
9475 tnc.begin()->second.erase(evicted);
9476 cnt.erase(val);
9477 um.erase(val);
9478 }
9479 } else {
9480 //未满
9481 if(um.contains(key)) {
9482 //已存在
9483 tnc[cnt[key] - 1].erase(find(tnc[cnt[key] - 1].begin(), tnc[cnt[key] - 1].end(), key));
9484 if(tnc[cnt[key] - 1].empty()) {
9485 tnc.erase(cnt[key] - 1);
9486 }
9487 } else {
9488 //不存在
9489 }
9490 }
9491 tnc[cnt[key]].emplace_back(key);
9492 um[key] = value;
9493 }
9494 }// namespace lfu_cache
9495
9496 namespace leetcode454_4sum_ii {
9497 int Solution::sumCount(int sum, int i) {
9498 if(mem[i].contains(sum)) {
9499 return mem[i][sum];
9500 }
9501 if(i == vec.size() - 1) {
9502 return vec[i][sum];
9503 }
9504 int ans = 0;
9505 for(const auto &[k, v]: vec[i]) {
9506 ans += v * sumCount(sum - k, i + 1);
9507 }
9508 mem[i][sum] = ans;
9509 return ans;
9510 }
9511
9512 int Solution::fourSumCount(vector<int> &nums1, vector<int> &nums2, vector<int> &nums3, vector<int> &nums4) {
9513 mem = vector<unordered_map<int, int>>(4);
9514 vec = vector<unordered_map<int, int>>(4);
9515 for(const auto &num: nums1) {
9516 vec[0][num]++;
9517 }
9518 for(const auto &num: nums2) {
9519 vec[1][num]++;
9520 }
9521 for(const auto &num: nums3) {
9522 vec[2][num]++;
9523 }
9524 for(const auto &num: nums4) {
9525 vec[3][num]++;
9526 }
9527 return sumCount(0, 0);
9528 }
9529 }// namespace leetcode454_4sum_ii
9530
9531 namespace maximum_size_subarray_sum_equals_k {
9532 int Solution::maxSubArrayLen(vector<int> &nums, int k) {
9533 auto pref_sum = vector(nums.size(), 0);
9534 pref_sum[0] = nums[0];
9535 unordered_map<int, set<int>> um;
9536 um[0].insert(-1);
9537 um[nums[0]].insert(0);
9538 for(int i = 1; i < nums.size(); i++) {
9539 pref_sum[i] += nums[i] + pref_sum[i - 1];
9540 um[pref_sum[i]].insert(i);
9541 }
9542 int ans = 0;
9543 for(int i = nums.size() - 1; i >= 0; i--) {
9544 const int r = pref_sum[i];
9545 int l = r - k;
9546 if(!um[l].empty()) {
9547 ans = max(ans, i - *um[l].begin());
9548 }
9549 }
9550 return ans;
9551 }
9552 }// namespace maximum_size_subarray_sum_equals_k
9553
9554 namespace minimum_swaps_to_group_all_1s_together {
9555 int Solution::minSwaps(vector<int> &data) {
9556 auto one_count = vector(data.size(), 0);
9557 int cnt1 = 0;
9558 for(int i = 0; i < one_count.size(); i++) {
9559 one_count[i] = cnt1 + data[i];
9560 cnt1 = one_count[i];
9561 }
9562 if(cnt1 == 0) {
9563 return 0;
9564 }
9565 int ans = cnt1 - one_count[cnt1 - 1];
9566 for(int i = 0; i + cnt1 < one_count.size(); i++) {
9567 ans = min(ans, cnt1 - (one_count[i + cnt1] - one_count[i]));
9568 }
9569 return ans;
9570 }
9571 }// namespace minimum_swaps_to_group_all_1s_together
9572}// namespace leetcode
void ms(vector< int > &arr, int l, int r, int *ans)
Definition: acwing.cpp:6334
bool cmp(const pair< int, int > &a, const pair< int, int > &b)
Definition: acwing.cpp:6470
bool find(vector< unordered_set< int > > &g, int x, vector< bool > &st, vector< int > &match)
Definition: acwing.cpp:7522
void reverse(struct ListNode *head)
vector< int > root
Definition: acwing408.cpp:349
void remove(TreeNode *&root, int x)
Definition: acwing408.cpp:476
unsigned long long qmi(unsigned long long m, unsigned long long k)
Definition: leetcode.cpp:5080
bool equal(TreeNode *tn1, TreeNode *tn2)
bool is_valid(int year, int month, int day)
Definition: pat.cpp:915
bool is_palindromic(string str)
Definition: pat.cpp:2767
int rmin[100010]
Definition: pat.cpp:5097
int lmax[100010]
Definition: pat.cpp:5096
int vec[100010]
Definition: pat.cpp:5095
TreeNode * left
Definition: leetcode.h:25
bool operator==(const TreeNode &) const
Definition: leetcode.cpp:19
TreeNode * right
Definition: leetcode.h:26
bool operator!=(const TreeNode &) const
Definition: leetcode.cpp:41
ListNode * next
Definition: leetcode.h:44
Node * next
Definition: leetcode.h:61
static vector< string > findAllConcatenatedWordsInADict(vector< string > &)
Definition: leetcode.cpp:44
bool dfs(TrieNode *, const string &, int, bool) const
Definition: leetcode.cpp:79
void insert(const string &str)
Definition: leetcode.cpp:66
static int titleToNumber(const string &columnTitle)
Definition: leetcode.cpp:108
static string convertToTitle(int columnNumber)
Definition: leetcode.cpp:119
int majorityElement(vector< int > &nums)
Definition: leetcode.cpp:149
static int countQuadruplets(vector< int > &)
Definition: leetcode.cpp:165
static bool isNStraightHand(vector< int > &hand, int groupSize)
Definition: leetcode.cpp:192
static bool checkPerfectNumber(int num)
Definition: leetcode.cpp:218
static void get_sum(FriendTreeNode *)
Definition: leetcode.cpp:257
static TreeNode * convertBST(TreeNode *root)
Definition: leetcode.cpp:235
static void convert(FriendTreeNode *)
Definition: leetcode.cpp:268
static FriendTreeNode * copy(TreeNode *)
Definition: leetcode.cpp:246
static vector< vector< int > > construct2DArray(vector< int > &original, int m, int n)
Definition: leetcode.cpp:284
static int numberOfBeams(vector< string > &)
Definition: leetcode.cpp:346
static bool asteroidsDestroyed(int mass, vector< int > &asteroids)
Definition: leetcode.cpp:380
static string dayOfTheWeek(int day, int month, int year)
Definition: leetcode.cpp:475
int getResult(int mouse, int cat, int turns)
Definition: leetcode.cpp:501
int dp[MAXN][MAXN][MAXN *2]
Definition: leetcode.h:236
int catMouseGame(vector< vector< int > > &graph)
Definition: leetcode.cpp:494
void getNextResult(int mouse, int cat, int turns)
Definition: leetcode.cpp:517
vector< vector< int > > graph
Definition: leetcode.h:237
static string simplifyPath(const string &path)
Definition: leetcode.cpp:560
static vector< int > grayCode(int n)
Definition: leetcode.cpp:615
static bool checkValid(vector< vector< int > > &matrix)
Definition: leetcode.cpp:625
static int wordCount(vector< string > &startWords, vector< string > &targetWords)
Definition: leetcode.cpp:692
static char slowestKey(vector< int > &releaseTimes, string keysPressed)
Definition: leetcode.cpp:723
static bool dfs(unsigned long long n1, unsigned long long n2, const char *, unsigned short length, unsigned short current)
Definition: leetcode.cpp:769
static bool isAdditiveNumber(string num)
Definition: leetcode.cpp:742
static unsigned long long str2ui(const char *, unsigned short start, unsigned short length)
将字符串的一个子串转换为整数
Definition: leetcode.cpp:787
static bool equal(string, const char *, unsigned short start, unsigned short length)
判断一个字符串与另一个字符串的子串是否相等
Definition: leetcode.cpp:796
static string decodeCiphertext(string encodedText, int rows)
Definition: leetcode.cpp:808
static string rtrim(string &s)
去除字符串右边的空白符
Definition: leetcode.cpp:838
bool operator==(const point &p) const
Definition: leetcode.cpp:902
bool operator<(const point &p) const
Definition: leetcode.cpp:901
size_t operator()(const point &p) const
Definition: leetcode.cpp:904
static bool isEscapePossible(vector< vector< int > > &blocked, vector< int > &source, vector< int > &target)
Definition: leetcode.cpp:850
static unsigned int search(unordered_set< point, point_hash > &block_set, point *source, point *target, unsigned int limit)
在迷宫中以source为起点搜索
Definition: leetcode.cpp:876
static bool increasingTriplet(vector< int > &nums)
Definition: leetcode.cpp:908
static vector< vector< int > > kSmallestPairs(vector< int > &nums1, vector< int > &nums2, int k)
Definition: leetcode.cpp:976
static vector< vector< int > > permute(vector< int > &nums)
Definition: leetcode.cpp:1000
static vector< string > divideString(const string &s, int k, char fill)
Definition: leetcode.cpp:1049
static int minMoves(int target, int maxDoubles)
Definition: leetcode.cpp:1067
static long long mostPoints(vector< vector< int > > &questions)
Definition: leetcode.cpp:1086
static long long maxRunTime(int n, vector< int > &batteries)
Definition: leetcode.cpp:1098
static int findMinDifference(vector< string > &timePoints)
Definition: leetcode.cpp:1142
static bool containsNearbyDuplicate(vector< int > &nums, int k)
Definition: leetcode.cpp:1158
static bool stoneGameIX(vector< int > &stones)
Definition: leetcode.cpp:1178
static int minJumps(vector< int > &arr)
Definition: leetcode.cpp:1204
TrieNode * next[26]
Definition: leetcode.h:567
void insert(const string &str)
Definition: leetcode.cpp:1282
string get_prefix(string root, const string &str) const
Definition: leetcode.cpp:1293
static string replaceWords(vector< string > &dictionary, const string &sentence)
Definition: leetcode.cpp:1264
static int numberOfArrays(vector< int > &differences, int lower, int upper)
Definition: leetcode.cpp:1324
static vector< vector< int > > highestRankedKItems(vector< vector< int > > &grid, vector< int > &pricing, vector< int > &start, int k)
Definition: leetcode.cpp:1338
static vector< int > rearrangeArray(vector< int > &nums)
Definition: leetcode.cpp:1464
static vector< int > findLonely(vector< int > &nums)
Definition: leetcode.cpp:1485
static int maximumGood(vector< vector< int > > &statements)
Definition: leetcode.cpp:1507
static pair< int, unordered_map< int, bool > > dfs(vector< vector< int > > &statements, unordered_map< int, bool > um, queue< msg > que)
Definition: leetcode.cpp:1528
void update(int timestamp, int price)
Definition: leetcode.cpp:1611
static int secondMinimum(int n, vector< vector< int > > &edges, int time, int change)
Definition: leetcode.cpp:1629
multiset< pair< int, int > > ms
Definition: leetcode.h:743
void add(vector< int > point)
Definition: leetcode.cpp:1704
int count(vector< int > point) const
Definition: leetcode.cpp:1706
static int countValidWords(const string &sentence)
Definition: leetcode.cpp:1718
static int numberOfWeakCharacters(vector< vector< int > > &properties)
Definition: leetcode.cpp:1765
static bool patternMatching(const string &pattern, const string &value)
Definition: leetcode.cpp:1783
static vector< vector< int > > highestPeak(vector< vector< int > > &isWater)
Definition: leetcode.cpp:1855
static vector< string > uncommonFromSentences(const string &s1, const string &s2)
Definition: leetcode.cpp:1896
static int findFinalValue(vector< int > &nums, int original)
Definition: leetcode.cpp:1931
static string subStrHash(string s, int power, int modulo, int k, int hashValue)
Definition: leetcode.cpp:1980
unordered_map< unsigned int, unsigned int > rank
Definition: leetcode.h:834
unordered_map< unsigned int, unsigned int > size
Definition: leetcode.h:835
unordered_map< unsigned int, unsigned int > parent
Definition: leetcode.h:833
static unsigned int compress(const string &word)
Definition: leetcode.cpp:2037
vector< int > groupStrings(vector< string > &words)
Definition: leetcode.cpp:2004
void to_union(unsigned int x1, unsigned int x2)
Definition: leetcode.cpp:2059
unsigned int find(unsigned int x)
Definition: leetcode.cpp:2057
static string longestNiceSubstring(const string &s)
Definition: leetcode.cpp:2100
static pair< int, int > dfs(string s, int start, int end)
Definition: leetcode.cpp:2108
static string reversePrefix(string word, char ch)
Definition: leetcode.cpp:2154
static int find_min(set< int, greater<> > &fibb, int k, set< int, greater<> >::iterator begin)
Definition: leetcode.cpp:2186
static int countGoodRectangles(vector< vector< int > > &rectangles)
Definition: leetcode.cpp:2196
static int get_sum(int current, int x, int y, int m, int n, vector< vector< int > > &grid, bool **occupied)
Definition: leetcode.cpp:2231
static int getMaximumGold(vector< vector< int > > &grid)
Definition: leetcode.cpp:2207
static vector< int > pivotArray(vector< int > &nums, int pivot)
Definition: leetcode.cpp:2268
static int get_cost(int startAt, int moveCost, int pushCost, const int num[4])
Definition: leetcode.cpp:2307
static int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds)
Definition: leetcode.cpp:2288
static int sumOfUnique(vector< int > &nums)
Definition: leetcode.cpp:2375
static vector< int > sortEvenOdd(vector< int > &nums)
Definition: leetcode.cpp:2391
set< unsigned int > * zero0
Definition: leetcode.h:977
Bitset(int size)
用 size 个位初始化 Bitset ,所有位都是 0 。
Definition: leetcode.cpp:2458
string toString() const
返回 Bitset 的当前组成情况。注意,在结果字符串中,第 i 个下标处的字符应该与 Bitset 中的第 i 位一致。
Definition: leetcode.cpp:2489
bool one() const
检查 Bitset 中 是否 至少一位 的值是 1 。如果满足此条件,返回 true ;否则,返回 false 。
Definition: leetcode.cpp:2485
void fix(int idx) const
将下标为 idx 的位上的值更新为 1 。如果值已经是 1 ,则不会发生任何改变。
Definition: leetcode.cpp:2467
bool all() const
检查 Bitset 中 每一位 的值是否都是 1 。如果满足此条件,返回 true ;否则,返回 false 。
Definition: leetcode.cpp:2483
void flip()
翻转 Bitset 中每一位上的值。换句话说,所有值为 0 的位将会变成 1 ,反之亦然。
Definition: leetcode.cpp:2477
set< unsigned int > * one1
Definition: leetcode.h:976
int count() const
返回 Bitset 中值为 1 的位的 总数 。
Definition: leetcode.cpp:2487
void unfix(int idx) const
将下标为 idx 的位上的值更新为 0 。如果值已经是 0 ,则不会发生任何改变。
Definition: leetcode.cpp:2472
static int * get_p(char ch, int *a, int *b, int *c)
Definition: leetcode.cpp:2573
static void sort(char ch[3], int a, int b, int c)
Definition: leetcode.cpp:2549
static string longestDiverseString(int a, int b, int c)
Definition: leetcode.cpp:2507
unsigned long long operator()(const pair< int, int > &) const
Definition: leetcode.cpp:2628
static vector< int > gridIllumination(int n, vector< vector< int > > &lamps, vector< vector< int > > &queries)
Definition: leetcode.cpp:2584
static vector< string > simplifiedFractions(int n)
Definition: leetcode.cpp:2646
static int numEnclaves(vector< vector< int > > &grid)
Definition: leetcode.cpp:2676
static int maxNumberOfBalloons(const string &text)
Definition: leetcode.cpp:2710
static bool canTransform(const string &start, const string &end)
Definition: leetcode.cpp:2747
static int countOperations(int num1, int num2)
Definition: leetcode.cpp:2788
static long long minimumRemoval(vector< int > &beans)
Definition: leetcode.cpp:2858
static int maximumANDSum(vector< int > &nums, int numSlots)
Definition: leetcode.cpp:2871
static int singleNonDuplicate(vector< int > &nums)
Definition: leetcode.cpp:2895
static vector< int > luckyNumbers(vector< vector< int > > &matrix)
Definition: leetcode.cpp:2929
static int checkWays(vector< vector< int > > &pairs)
Definition: leetcode.cpp:2957
static int findCenter(vector< vector< int > > &edges)
Definition: leetcode.cpp:3013
unsigned int operator()(const status &) const
Definition: leetcode.cpp:3058
bool operator()(const status &, const status &) const
Definition: leetcode.cpp:3060
unordered_map< status, double, status_hash, status_equal > um
Definition: leetcode.h:1185
double knightProbability(int n, int k, int row, int column)
Definition: leetcode.cpp:3030
static vector< int > pancakeSort(vector< int > &arr)
Definition: leetcode.cpp:3064
static vector< long long > maximumEvenSplit(long long finalSum)
Definition: leetcode.cpp:3127
static long long goodTriplets(vector< int > &nums1, vector< int > &nums2)
Definition: leetcode.cpp:3152
static ListNode * mergeNodes(ListNode *head)
Definition: leetcode.cpp:3192
static string repeatLimitedString(const string &s, int repeatLimit)
Definition: leetcode.cpp:3211
static long long coutPairs(vector< int > &nums, int k)
Definition: leetcode.cpp:3243
static int longestMountain(vector< int > &arr)
Definition: leetcode.cpp:3288
static string pushDominoes(string dominoes)
Definition: leetcode.cpp:3329
static int numberOfGoodSubsets(vector< int > &nums)
Definition: leetcode.cpp:3391
static constexpr array< int, 10 > primes
Definition: leetcode.h:1323
static string reverseOnlyLetters(string s)
Definition: leetcode.cpp:3442
static vector< int > findBall(vector< vector< int > > &grid)
Definition: leetcode.cpp:3464
static string complexNumberMultiply(const string &num1, const string &num2)
Definition: leetcode.cpp:3521
static string optimalDivision(vector< int > &nums)
Definition: leetcode.cpp:3558
static int prefixCount(vector< string > &words, string pref)
Definition: leetcode.cpp:3576
static long long minimumTime(vector< int > &time, int totalTrips)
Definition: leetcode.cpp:3613
static int minimumFinishTime(vector< vector< int > > &tires, int changeTime, int numLaps)
Definition: leetcode.cpp:3642
static int maximumRequests(int n, vector< vector< int > > &requests)
Definition: leetcode.cpp:3676
static string convert(string s, int numRows)
Definition: leetcode.cpp:3707
static string nearestPalindromic(const string &n)
Definition: leetcode.cpp:3748
static int addDigits(int num)
Definition: leetcode.cpp:3789
static long long subArrayRanges(vector< int > &nums)
Definition: leetcode.cpp:3793
static int findLUSlength(const string &a, const string &b)
Definition: leetcode.cpp:3809
static int mostFrequent(vector< int > &nums, int key)
Definition: leetcode.cpp:3818
static vector< int > sortJumbled(vector< int > &mapping, vector< int > &nums)
Definition: leetcode.cpp:3838
vector< vector< int > > getAncestors(int n, vector< vector< int > > &edges)
Definition: leetcode.cpp:3859
static vector< string > cellsInRange(const string &s)
Definition: leetcode.cpp:3924
static long long minimalKSum(vector< int > &nums, int k)
Definition: leetcode.cpp:3946
static TreeNode * createBinaryTree(vector< vector< int > > &descriptions)
Definition: leetcode.cpp:3965
static vector< int > replaceNonCoprimes(vector< int > &nums)
Definition: leetcode.cpp:3996
static vector< int > goodDaysToRobBank(vector< int > &security, int time)
Definition: leetcode.cpp:4011
static string convertToBase7(int num)
Definition: leetcode.cpp:4046
static vector< int > platesBetweenCandles(string s, vector< vector< int > > &queries)
Definition: leetcode.cpp:4072
static vector< int > preorder(Node *root)
Definition: leetcode.cpp:4138
const vector< TreeNode * > & get_children() const
Definition: leetcode.cpp:4204
static int countHighestScoreNodes(vector< int > &parents)
Definition: leetcode.cpp:4153
static vector< int > postorder(Node *root)
Definition: leetcode.cpp:4212
unordered_map< pair< int, int >, int, function< unsigned int(const pair< int, int > &)> > size
Definition: leetcode.h:1670
unordered_map< pair< int, int >, int, function< unsigned int(const pair< int, int > &)> > rank
Definition: leetcode.h:1671
bool same(pair< int, int > a, pair< int, int > b)
Definition: leetcode.cpp:4307
int get_size(pair< int, int > p)
Definition: leetcode.cpp:4311
void merge(pair< int, int > a, pair< int, int > b)
Definition: leetcode.cpp:4289
bool contains(pair< int, int > p) const
Definition: leetcode.cpp:4309
unordered_map< pair< int, int >, pair< int, int >, function< unsigned int(const pair< int, int > &)> > parent
Definition: leetcode.h:1669
pair< int, int > find(pair< int, int > val)
Definition: leetcode.cpp:4282
static int maxAreaOfIsland(vector< vector< int > > &grid)
Definition: leetcode.cpp:4227
static vector< int > findKDistantIndices(vector< int > &nums, int key, int k)
Definition: leetcode.cpp:4315
static int digArtifacts(int n, vector< vector< int > > &artifacts, vector< vector< int > > &dig)
Definition: leetcode.cpp:4335
static int maximumTop(vector< int > &nums, int k)
Definition: leetcode.cpp:4371
static void calc_dist(int s, vector< pair< int, int > > *graph, vector< long long int > &dist)
Definition: leetcode.cpp:4444
static long long minimumWeight(int n, vector< vector< int > > &edges, int src1, int src2, int dest)
Definition: leetcode.cpp:4405
static bool validUtf8(vector< int > &data)
Definition: leetcode.cpp:4465
static vector< string > findRestaurant(vector< string > &list1, vector< string > &list2)
Definition: leetcode.cpp:4506
static int dfs(int current, int target, vector< int > nums)
Definition: leetcode.cpp:4549
AllOne()
Initializes the object of the data structure.
Definition: leetcode.cpp:4564
string getMaxKey()
Returns one of the keys with the maximal count.
Definition: leetcode.cpp:4606
string getMinKey()
Returns one of the keys with the minimum count.
Definition: leetcode.cpp:4613
map< int, unordered_set< string > > count_str
Definition: leetcode.h:1752
void dec(const string &key)
Decrements the count of the string key by 1. If the count of key is 0 after the decrement,...
Definition: leetcode.cpp:4585
unordered_map< string, int > str_count
Definition: leetcode.h:1751
void inc(const string &key)
Increments the count of the string key by 1. If key does not exist in the data structure,...
Definition: leetcode.cpp:4569
static string longestWord(vector< string > &words)
Definition: leetcode.cpp:4622
static string dfs(const string &str, TrieNode *node)
Definition: leetcode.cpp:4630
bool transfer(int account1, int account2, long long money)
Transfers money dollars from the account numbered account1 to the account numbered account2.
Definition: leetcode.cpp:4652
bool withdraw(int account, long long money)
Withdraw money dollars from the account numbered account.
Definition: leetcode.cpp:4672
bool deposit(int account, long long money)
Deposit money dollars into the account numbered account.
Definition: leetcode.cpp:4664
Bank(vector< long long > &balance)
Initializes the object with the 0-indexed integer array balance.
Definition: leetcode.cpp:4645
unordered_map< int, long long > accounts
Definition: leetcode.h:1782
static long long maximumSubsequenceCount(string text, string pattern)
Definition: leetcode.cpp:4701
static int minimumWhiteTiles(string floor, int numCarpets, int carpetLen)
Definition: leetcode.cpp:4751
static int countCollisions(const string &directions)
Definition: leetcode.cpp:4783
static vector< int > maximumBobPoints(int numArrows, vector< int > &aliceArrows)
Definition: leetcode.cpp:4817
static int networkBecomesIdle(vector< vector< int > > &edges, vector< int > &patience)
Definition: leetcode.cpp:4851
static bool findTarget(TreeNode *root, int k)
Definition: leetcode.cpp:4894
static vector< vector< int > > imageSmoother(vector< vector< int > > &img)
Definition: leetcode.cpp:4985
static int calPoints(vector< string > &ops)
Definition: leetcode.cpp:5029
static vector< long long > kthPalindrome(vector< int > &queries, int intLength)
Definition: leetcode.cpp:5093
static vector< int > missingRolls(vector< int > &rolls, int mean, int n)
Definition: leetcode.cpp:5177
static int maxConsecutiveAnswers(string answerKey, int k)
Definition: leetcode.cpp:5214
static vector< int > busiestServers(int k, vector< int > &arrival, vector< int > &load)
Definition: leetcode.cpp:5262
static vector< int > selfDividingNumbers(int left, int right)
Definition: leetcode.cpp:5311
static bool canReorderDoubled(vector< int > &arr)
Definition: leetcode.cpp:5338
static int strongPasswordChecker(const string &password)
Definition: leetcode.cpp:5373
static int convertTime(string current, string correct)
Definition: leetcode.cpp:5530
static vector< vector< int > > findWinners(vector< vector< int > > &matches)
Definition: leetcode.cpp:5555
static int maximumCandies(vector< int > &candies, long long k)
Definition: leetcode.cpp:5581
Encrypter(vector< char > &keys, vector< string > &values, vector< string > &dictionary)
用 keys、values 和 dictionary 初始化 Encrypter 类。
Definition: leetcode.cpp:5625
int decrypt(const string &word2)
统计可以由 word2 解密得到且出现在 dictionary 中的字符串数目
Definition: leetcode.cpp:5646
string encrypt(const string &word1) const
按上述加密过程完成对 word1 的加密
Definition: leetcode.cpp:5634
NumArray(vector< int > &nums)
Initializes the object with the integer array nums.
Definition: leetcode.cpp:5657
void update(int index, int val)
Updates the value of nums[index] to be val.
Definition: leetcode.cpp:5667
int sumRange(int left, int right) const
Returns the sum of the elements of nums between indices left and right inclusive (i....
Definition: leetcode.cpp:5672
static vector< bool > friendRequests(int n, vector< vector< int > > &restrictions, vector< vector< int > > &requests)
Definition: leetcode.cpp:5689
static vector< int > findMinHeightTrees(int n, vector< vector< int > > &edges)
Definition: leetcode.cpp:5736
static int findLongestNode(int u, vector< int > &parent, vector< vector< int > > &adj)
Definition: leetcode.cpp:5765
static bool rotateString(string s, const string &goal)
Definition: leetcode.cpp:5790
static vector< vector< int > > levelOrder(Node *root)
Definition: leetcode.cpp:5800
static bool reachingPoints(int sx, int sy, int tx, int ty)
Definition: leetcode.cpp:5823
static int maximumProduct(vector< int > &nums, int k)
Definition: leetcode.cpp:5845
static long long maximumBeauty(vector< int > &flowers, long long newFlowers, int target, int full, int partial)
Definition: leetcode.cpp:5867
static vector< int > numberOfLines(vector< int > &widths, string s)
Definition: leetcode.cpp:5914
static bool checkInclusion(const string &s1, string s2)
Definition: leetcode.cpp:5929
int getRandom()
Returns a random element from the current set of elements (it's guaranteed that at least one element ...
Definition: leetcode.cpp:5986
bool insert(int val)
Inserts an item val into the set if not present.
Definition: leetcode.cpp:5964
RandomizedSet()
Initializes the RandomizedSet object.
Definition: leetcode.cpp:5959
bool remove(int val)
Removes an item val from the set if present.
Definition: leetcode.cpp:5973
uniform_int_distribution< int > distribution
Definition: leetcode.h:2221
static int projectionArea(vector< vector< int > > &grid)
Definition: leetcode.cpp:5990
int medium
The number of slots for medium parking space
Definition: leetcode.h:2249
ParkingSystem(int big, int medium, int small)
Initializes object of the ParkingSystem class.
Definition: leetcode.cpp:6023
int big
The number of slots for big parking space
Definition: leetcode.h:2248
bool addCar(int carType)
Checks whether there is a parking space of carType for the car that wants to get into the parking lot...
Definition: leetcode.cpp:6026
int small
The number of slots for small parking space
Definition: leetcode.h:2250
NumArray(vector< int > &nums)
Initializes the object with the integer array nums.
Definition: leetcode.cpp:6055
int sumRange(int left, int right) const
Returns the sum of the elements of nums between indices left and right inclusive (i....
Definition: leetcode.cpp:6063
static int rob(vector< int > &nums)
Definition: leetcode.cpp:6067
static int minimumTotal(vector< vector< int > > &triangle)
Definition: leetcode.cpp:6082
static TreeNode * lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
Definition: leetcode.cpp:6104
static void copy(TreeNode *tn, TreeNodeP *tnp, int low, int high, TreeNodeP **p, TreeNodeP **q)
Definition: leetcode.cpp:6124
vector< int > shuffle() const
Returns a random shuffling of the array.
Definition: leetcode.cpp:6147
Solution(vector< int > &nums)
Initializes the object with the integer array nums.
Definition: leetcode.cpp:6158
vector< int > reset()
Resets the array to its original configuration and returns it.
Definition: leetcode.cpp:6145
static vector< int > findAnagrams(string s, const string &p)
Definition: leetcode.cpp:6163
static int numSubarrayProductLessThanK(vector< int > &nums, int k)
Definition: leetcode.cpp:6191
static int minSubArrayLen(int target, vector< int > &nums)
Definition: leetcode.cpp:6208
static bool isSubtree(TreeNode *root, TreeNode *subRoot)
Definition: leetcode.cpp:6276
static bool equal(TreeNode *tn1, TreeNode *tn2)
Definition: leetcode.cpp:6298
static int shortestPathBinaryMatrix(vector< vector< int > > &grid)
Definition: leetcode.cpp:6319
static void solve(vector< vector< char > > &board)
Definition: leetcode.cpp:6362
static void dfs(vector< vector< char > > &board, int x, int y)
Definition: leetcode.cpp:6393
static int dfs(vector< vector< int > > &graph, vector< vector< int > > &ans, int cur)
Definition: leetcode.cpp:6417
static vector< vector< int > > allPathsSourceTarget(vector< vector< int > > &graph)
Definition: leetcode.cpp:6407
static vector< vector< int > > permuteUnique(vector< int > &nums)
Definition: leetcode.cpp:6435
static void dfs(set< vector< int > > &s, const vector< int > &current, vector< int > rest)
Definition: leetcode.cpp:6446
static vector< vector< int > > combinationSum(vector< int > &candidates, int target)
Definition: leetcode.cpp:6462
static vector< vector< int > > recurse(vector< int > &candidates, int target, int index)
Definition: leetcode.cpp:6467
static vector< vector< int > > combinationSum2(vector< int > &candidates, int target)
Definition: leetcode.cpp:6486
static vector< vector< int > > recurse(vector< int > &candidates, int target, int index)
Definition: leetcode.cpp:6499
static int rob(vector< int > &nums)
Definition: leetcode.cpp:6520
static bool canJump(vector< int > &nums)
Definition: leetcode.cpp:6531
static int jump(vector< int > &nums)
Definition: leetcode.cpp:6548
static int uniquePaths(int m, int n)
Definition: leetcode.cpp:6566
static int numberOfArithmeticSlices(vector< int > &nums)
Definition: leetcode.cpp:6632
static int numDecodings(string s)
Definition: leetcode.cpp:6662
static void search(const TrieNode *tn, const string &s, int i, vector< bool > &end)
Definition: leetcode.cpp:6701
static bool wordBreak(const string &s, vector< string > &wordDict)
Definition: leetcode.cpp:6683
static int lengthOfLIS(vector< int > &nums)
Definition: leetcode.cpp:6716
static int longestCommonSubsequence(string text1, string text2)
Definition: leetcode.cpp:6758
static int minDistance(const string &word1, const string &word2)
Definition: leetcode.cpp:6774
static int minDistance(string word1, string word2)
Definition: leetcode.cpp:6781
static int coinChange(vector< int > &coins, int amount)
Definition: leetcode.cpp:6805
static int maxPoints(vector< vector< int > > &points)
Definition: leetcode.cpp:6850
static vector< vector< string > > groupAnagrams(vector< string > &strs)
Definition: leetcode.cpp:6872
static void qsort(vector< int > &nums, int l, int r)
Definition: leetcode.cpp:6896
static void sortColors(vector< int > &nums)
Definition: leetcode.cpp:6894
static vector< int > topKFrequent(vector< int > &nums, int k)
Definition: leetcode.cpp:6916
static int findKthLargest(vector< int > &nums, int k)
Definition: leetcode.cpp:6942
static vector< vector< int > > merge(vector< vector< int > > &intervals)
Definition: leetcode.cpp:6949
static bool searchMatrix(vector< vector< int > > &matrix, int target)
Definition: leetcode.cpp:6970
static bool search(const vector< vector< int > > &matrix, int target, int x_start, int x_end, int y_start, int y_end)
Definition: leetcode.cpp:6972
static TreeNode * deserialize(string data)
Decodes your encoded data to tree.
Definition: leetcode.cpp:7045
static string serialize(TreeNode *root)
Encodes a tree to a single string.
Definition: leetcode.cpp:7013
static int leastInterval(vector< char > &tasks, int n)
Definition: leetcode.cpp:7075
MyHashMap()
initializes the object with an empty map.
Definition: leetcode.cpp:7116
void put(int key, int value)
inserts a (key, value) pair into the HashMap. If the key already exists in the map,...
Definition: leetcode.cpp:7123
static const unsigned SZ
Definition: leetcode.h:2626
void remove(int key)
removes the key and its corresponding value if the map contains the mapping for the key.
Definition: leetcode.cpp:7144
array< list< pair< int, int > >, SZ > arr
Definition: leetcode.h:2627
static vector< vector< int > > generateMatrix(int n)
Definition: leetcode.cpp:7156
static int eraseOverlapIntervals(vector< vector< int > > &intervals)
Definition: leetcode.cpp:7196
static vector< int > productExceptSelf(vector< int > &nums)
Definition: leetcode.cpp:7217
static int subarraySum(vector< int > &nums, int k)
Definition: leetcode.cpp:7239
static vector< int > partitionLabels(string s)
Definition: leetcode.cpp:7254
static vector< string > findRepeatedDnaSequences(string s)
Definition: leetcode.cpp:7274
int get(int index) const
Get the value of the indexth node in the linked list. If the index is invalid, return -1.
Definition: leetcode.cpp:7328
void deleteAtIndex(int index)
Delete the indexth node in the linked list, if the index is valid.
Definition: leetcode.cpp:7376
void addAtHead(int val)
Add a node of value val before the first element of the linked list. After the insertion,...
Definition: leetcode.cpp:7340
void addAtTail(int val)
Append a node of value val as the last element of the linked list.
Definition: leetcode.cpp:7349
void addAtIndex(int index, int val)
Add a node of value val before the indexth node in the linked list. If index equals the length of the...
Definition: leetcode.cpp:7355
MyLinkedList()
Initializes the MyLinkedList object.
Definition: leetcode.cpp:7323
TreeNode * deleteNode(TreeNode *root, int key)
Definition: leetcode.cpp:7445
TreeNode * findMinimum(TreeNode *node)
Definition: leetcode.cpp:7409
TreeNode * findMaximum(TreeNode *node)
Definition: leetcode.cpp:7400
static unsigned missing(vector< int > &nums, int i)
Definition: leetcode.cpp:7497
static int missingElement(vector< int > &nums, int k)
Definition: leetcode.cpp:7473
static vector< int > findPeakGridLR(vector< vector< int > > &mat, int l, int r)
Definition: leetcode.cpp:7501
static int get(vector< vector< int > > &mat, int i, int j)
Definition: leetcode.cpp:7526
static vector< int > findPeakGrid(vector< vector< int > > &mat)
Definition: leetcode.cpp:7524
static int count(vector< int > &sweetness, int x)
Definition: leetcode.cpp:7557
static int maximizeSweetness(vector< int > &sweetness, int k)
Definition: leetcode.cpp:7535
static vector< int > shortestDistanceColor(vector< int > &colors, vector< vector< int > > &queries)
Definition: leetcode.cpp:7572
static vector< int > minAvailableDuration(vector< vector< int > > &slots1, vector< vector< int > > &slots2, int duration)
Definition: leetcode.cpp:7602
static pair< int, int > merge(const vector< int > &vec1, const vector< int > &vec2)
Definition: leetcode.cpp:7626
static int countInRange(vector< int > &nums, int l, int r)
Definition: leetcode.cpp:7653
static int findDuplicate(vector< int > &nums)
Definition: leetcode.cpp:7630
static int trap(vector< int > &height)
Definition: leetcode.cpp:7665
static vector< vector< int > > findRLEArray(vector< vector< int > > &encoded1, vector< vector< int > > &encoded2)
Definition: leetcode.cpp:7687
static int cntMinFlip(vector< int > &nums, int len)
Definition: leetcode.cpp:7785
static int longestOnes(vector< int > &nums, int k)
Definition: leetcode.cpp:7770
static vector< int > maxSlidingWindow(vector< int > &nums, int k)
Definition: leetcode.cpp:7810
static string minWindow(string s, const string &t)
Definition: leetcode.cpp:7827
static bool valid(unordered_map< char, int > &ums, const unordered_map< char, int > &umt)
Definition: leetcode.cpp:7859
static void wallsAndGates(vector< vector< int > > &rooms)
Definition: leetcode.cpp:7870
size_t operator()(const pair< int, int > &p) const
Definition: leetcode.cpp:7956
bool operator()(const pair< int, int > &p1, const pair< int, int > &p2) const
Definition: leetcode.cpp:7954
static vector< vector< int > > pacificAtlantic(vector< vector< int > > &heights)
Definition: leetcode.cpp:7896
static vector< int > getLonelyNodes(TreeNode *root)
Definition: leetcode.cpp:7960
unordered_set< Node * > children
Definition: leetcode.h:2880
static vector< int > killProcess(vector< int > &pid, vector< int > &ppid, int kill)
Definition: leetcode.cpp:7984
static vector< int > distanceK(TreeNode *root, TreeNode *target, int k)
Definition: leetcode.cpp:8010
static int openLock(vector< string > &deadends, const string &target)
Definition: leetcode.cpp:8059
static int makeConnected(int n, vector< vector< int > > &connections)
Definition: leetcode.cpp:8105
static void dfs(int &edge_cnt, int &node_cnt, unordered_set< int > &vis, int node, vector< unordered_set< int > > &g)
Definition: leetcode.cpp:8129
bool operator()(const pair< int, Node * > &p1, const pair< int, Node * > &p2) const
Definition: leetcode.cpp:8202
static void tarjan(int prev, int &step, vector< int > &dfn, int node, vector< unordered_set< int > > &g, vector< int > &low, vector< vector< int > > &ans)
Definition: leetcode.cpp:8231
static vector< vector< int > > criticalConnections(int n, vector< vector< int > > &connections)
Definition: leetcode.cpp:8211
static vector< vector< int > > getFactorsWithMin(int n, int minimum)
Definition: leetcode.cpp:8249
static vector< vector< int > > getFactors(int n)
Definition: leetcode.cpp:8264
static string decodeString(string s)
Definition: leetcode.cpp:8268
static bool valid(const vector< vector< bool > > &board, int n, int x, int y)
Definition: leetcode.cpp:8329
static vector< string > toStringVec(const vector< vector< bool > > &board)
Definition: leetcode.cpp:8348
static void dfs(const vector< vector< bool > > &board, int line, int n, vector< vector< string > > &ans)
Definition: leetcode.cpp:8315
static vector< vector< string > > solveNQueens(int n)
Definition: leetcode.cpp:8308
static bool valid(const vector< vector< char > > &board, int x, int y, char num)
Definition: leetcode.cpp:8386
static bool dfs(const vector< vector< char > > &board, vector< vector< char > > &ans)
Definition: leetcode.cpp:8364
static void solveSudoku(vector< vector< char > > &board)
Definition: leetcode.cpp:8362
static bool isMatch(const string &s, const string &p)
Definition: leetcode.cpp:8409
static bool dfs(const string &s, const string &p, int si, int pi)
Definition: leetcode.cpp:8411
static vector< int > diffWaysToCompute(const string &expression)
Definition: leetcode.cpp:8488
static vector< int > eval(const string &expr, int start, int end)
Definition: leetcode.cpp:8452
static bool isValid(const string &str)
Definition: leetcode.cpp:8525
static vector< string > removeInvalidParentheses(const string &s)
Definition: leetcode.cpp:8496
static double findMedianSortedArrays(vector< int > &nums1, vector< int > &nums2)
Definition: leetcode.cpp:8544
vector< int > countSmaller(vector< int > &nums)
Definition: leetcode.cpp:8582
static int get_m(const vector< int > &nums, int msum)
Definition: leetcode.cpp:8686
static int splitArray(vector< int > &nums, int m)
Definition: leetcode.cpp:8665
size_t operator()(const pair< TreeNode *, bool > &p) const
Definition: leetcode.cpp:8728
bool operator()(const pair< TreeNode *, bool > &p1, const pair< TreeNode *, bool > &p2) const
Definition: leetcode.cpp:8730
int dfs(bool steal, TreeNode *node)
Definition: leetcode.cpp:8709
unordered_map< pair< TreeNode *, bool >, int, myhash, myeq > um
Definition: leetcode.h:3084
static int maximalSquare(vector< vector< char > > &matrix)
Definition: leetcode.cpp:8734
static int maximalRectangle(vector< vector< char > > &matrix)
Definition: leetcode.cpp:8776
static bool PredictTheWinner(vector< int > &nums)
Definition: leetcode.cpp:8825
static vector< vector< string > > partition(const string &s)
Definition: leetcode.cpp:8842
static void dfs(const vector< string > &current, const string &s, vector< vector< string > > &ans, int start, int cursor)
Definition: leetcode.cpp:8858
static bool is_palindromic(const string &s, int start, int end)
Definition: leetcode.cpp:8849
static bool canPartition(vector< int > &nums)
Definition: leetcode.cpp:8909
static int mincostTickets(vector< int > &days, vector< int > &costs)
Definition: leetcode.cpp:8943
static int calculateMinimumHP(vector< vector< int > > &dungeon)
Definition: leetcode.cpp:8989
static bool canFinish(int numCourses, vector< vector< int > > &prerequisites)
Definition: leetcode.cpp:9004
static vector< int > findOrder(int numCourses, vector< vector< int > > &prerequisites)
Definition: leetcode.cpp:9035
int longestIncreasingPath(vector< vector< int > > &matrix)
Definition: leetcode.cpp:9066
static int minimumSemesters(int n, vector< vector< int > > &relations)
Definition: leetcode.cpp:9115
static string alienOrder(vector< string > &words)
Definition: leetcode.cpp:9154
static vector< int > singleNumber(vector< int > &nums)
Definition: leetcode.cpp:9221
static int shortestPathAllKeys(vector< string > &grid)
Definition: leetcode.cpp:9241
static int minKBitFlips(vector< int > &nums, int k)
Definition: leetcode.cpp:9337
unordered_map< string, unordered_map< string, vector< int > > > um
Definition: leetcode.h:3264
unordered_map< int, pair< string, int > > records
Definition: leetcode.h:3265
void checkOut(int id, const string &stationName, int t)
通行卡 ID 等于 id 的乘客,在时间 t ,从 stationName 站离开
Definition: leetcode.cpp:9360
double getAverageTime(const string &startStation, const string &endStation)
平均时间会根据截至目前所有从 startStation 站 直接 到达 endStation 站的行程进行计算,也就是从 startStation 站进入并从 endStation 离开的行程 从 st...
Definition: leetcode.cpp:9362
void checkIn(int id, const string &stationName, int t)
通行卡 ID 等于 id 的乘客,在时间 t ,从 stationName 站进入 乘客一次只能从一个站进入
Definition: leetcode.cpp:9359
void put(int key, int value)
如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
Definition: leetcode.cpp:9386
LRUCache(int capacity)
以 正整数 作为容量 capacity 初始化 LRU 缓存
Definition: leetcode.cpp:9372
int get(int key)
如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
Definition: leetcode.cpp:9375
unordered_map< int, int > um
Definition: leetcode.h:3287
string get(const string &key, int timestamp)
返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp 。
Definition: leetcode.cpp:9419
unordered_map< string, map< int, string, greater< int > > > um
Definition: leetcode.h:3302
void set(const string &key, string value, int timestamp)
存储键 key、值 value,以及给定的时间戳 timestamp。
Definition: leetcode.cpp:9417
void assign(unsigned l, unsigned r, type val=false)
Definition: leetcode.h:3344
bool check(unsigned l, unsigned r)
Definition: leetcode.h:3350
void removeRange(int left, int right)
停止跟踪 半开区间 [left, right) 中当前正在跟踪的每个实数。
Definition: leetcode.cpp:9430
void addRange(int left, int right)
添加 半开区间 [left, right),跟踪该区间中的每个实数。添加与当前跟踪的数字部分重叠的区间时,应当添加在区间 [left, right) 中尚未跟踪的任何数字到该区间中。
Definition: leetcode.cpp:9426
bool queryRange(int left, int right)
只有在当前正在跟踪区间 [left, right) 中的每一个实数时,才返回 true ,否则返回 false 。
Definition: leetcode.cpp:9428
int get(int key)
如果键 key 存在于缓存中,则获取键的值,否则返回 -1 。
Definition: leetcode.cpp:9434
unordered_map< int, int > um
Definition: leetcode.h:3374
map< int, list< int > > tnc
Definition: leetcode.h:3376
unordered_map< int, int > cnt
Definition: leetcode.h:3375
void put(int key, int value)
如果键 key 已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量 capacity 时,则应该在插入新项之前,移除最不经常使用的项。在此问题中,当存在平局(即两个或更多个键具有相同使用频...
Definition: leetcode.cpp:9455
vector< unordered_map< int, int > > mem
Definition: leetcode.h:3393
int fourSumCount(vector< int > &nums1, vector< int > &nums2, vector< int > &nums3, vector< int > &nums4)
Definition: leetcode.cpp:9512
vector< unordered_map< int, int > > vec
Definition: leetcode.h:3394
static int maxSubArrayLen(vector< int > &nums, int k)
Definition: leetcode.cpp:9532
字典树节点
Definition: templates.h:9
array< TrieNode *, 26 > nexts
Definition: templates.h:11
void insert(const string &str)
Definition: templates.cpp:9
bool end_of_word
Definition: templates.h:12
并查集
Definition: templates.h:91
void unite(int x, int y)
Definition: templates.cpp:496
int find(int x)
Definition: templates.cpp:489