C++ to Java Conversion: Efficiently Finding Gaps in 2D Grids
import java.util.*;
public class GridGaps {
static final int N = 60009;
static final int INF = 0x3f3f3f3f;
static final double EPS = 1e-8;
static ArrayList<Integer> Lx[] = new ArrayList[N];
static ArrayList<Integer> Ly[] = new ArrayList[N];
static int n, m, k;
static int fin(int x, int y) {
int l = 0, r = Lx[x].size() - 1, mid, ans = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (Lx[x].get(mid) <= y) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (Lx[x].get(ans) == y && Lx[x].get(ans + 1) == y + 2) return 1;
return 0;
}
static int solve() {
int ret = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < Lx[i].size(); j++) {
if (Lx[i].get(j) - Lx[i].get(j - 1) > 2) {
ret++;
}
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < Ly[i].size(); j++) {
if (Ly[i].get(j) - Ly[i].get(j - 1) > 2) {
ret++;
}
if (Ly[i].get(j) - Ly[i].get(j - 1) == 2) {
if (fin(Ly[i].get(j) - 1, i - 1)) {
ret++;
}
}
}
}
return ret;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
int a, b;
Lx = new ArrayList[n + 1];
Ly = new ArrayList[m + 1];
for (int i = 0; i <= n; i++) {
Lx[i] = new ArrayList<>();
}
for (int i = 0; i <= m; i++) {
Ly[i] = new ArrayList<>();
}
for (int i = 0; i < k; i++) {
a = sc.nextInt();
b = sc.nextInt();
Lx[a].add(b);
Ly[b].add(a);
}
n++;
m++;
for (int i = 1; i <= n; i++) {
Lx[i].add(0);
Lx[i].add(m);
}
for (int i = 1; i <= m; i++) {
Ly[i].add(0);
Ly[i].add(n);
}
for (int i = 1; i <= n; i++) {
Collections.sort(Lx[i]);
}
for (int i = 1; i <= m; i++) {
Collections.sort(Ly[i]);
}
System.out.println(solve());
}
}
原文地址: https://www.cveoy.top/t/topic/n1LI 著作权归作者所有。请勿转载和采集!