Successful Pairs of Spells and Potions
Time complexity: $O(n^2\log M)$
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
class Solution {
public:
int maxPartitionFactor(std::vector<std::vector<int>>& points) {
int n = points.size();
if (n == 2) {
return 0;
}
std::vector<std::vector<int>> graph(n, std::vector<int>(n, 0x7fff'ffff));
int left = 0, right = 0;
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
graph[i][j] = graph[j][i] = mdist(points[i], points[j]);
right = std::max(graph[i][j], right);
}
}
while (right >= left) {
int mid = (left + right) / 2;
if (check(graph, n, mid)) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return right;
}
private:
bool check(std::vector<std::vector<int>>& graph, int n, int minDist) {
std::vector<int> visited(n, 0);
std::queue<int> q;
for (int i = 0; i < n; ++i) {
if (visited[i]) {
continue;
}
visited[i] = 1;
q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v = 0; v < n; ++v) {
if (graph[u][v] >= minDist) {
continue;
}
if (visited[v] == 0) {
visited[v] = -visited[u];
q.push(v);
}
else if (visited[v] == visited[u]) {
return false;
}
}
}
}
return true;
}
int mdist(std::vector<int>& a, std::vector<int>& b) {
return std::abs(a[0] - b[0]) + std::abs(a[1] - b[1]);
}
};
|
