Magic star Intensity code
Fri Nov 29 2024 16:38:45 GMT+0000 (Coordinated Universal Time)
Saved by @Asad_ullah
import java.util.*;
public class Main {
static class Line {
int x1, y1, x2, y2;
public Line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
private static int countCells(Line line, Pair<Integer, Integer> star, boolean split) {
if (line.x1 == line.x2) {
if (split) {
return Math.min(Math.abs(star.second - line.y1), Math.abs(star.second - line.y2)) + 1;
} else {
return Math.abs(line.y1 - line.y2) + 1;
}
} else {
if (split) {
return Math.min(Math.abs(star.first - line.x1), Math.abs(star.first - line.x2)) + 1;
} else {
return Math.abs(line.x1 - line.x2) + 1;
}
}
}
private static boolean intersects(Line a, Line b, Pair<Integer, Integer> intersection) {
if (a.x1 == a.x2 && b.y1 == b.y2) {
if (b.x1 <= a.x1 && a.x1 <= b.x2 && a.y1 <= b.y1 && b.y1 <= a.y2) {
intersection.set(a.x1, b.y1);
return true;
}
}
if (a.y1 == a.y2 && b.x1 == b.x2) {
if (a.x1 <= b.x1 && b.x1 <= a.x2 && b.y1 <= a.y1 && a.y1 <= b.y2) {
intersection.set(b.x1, a.y1);
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
List<Line> lines = new ArrayList<>();
for (int i = 0; i < N; ++i) {
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
if (x1 > x2 || (x1 == x2 && y1 > y2)) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
lines.add(new Line(x1, y1, x2, y2));
}
int K = sc.nextInt();
Map<Pair<Integer, Integer>, List<Line>> stars = new HashMap<>();
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
Pair<Integer, Integer> intersection = new Pair<>(0, 0);
if (intersects(lines.get(i), lines.get(j), intersection)) {
stars.computeIfAbsent(intersection, k -> new ArrayList<>()).add(lines.get(i));
stars.computeIfAbsent(intersection, k -> new ArrayList<>()).add(lines.get(j));
}
}
}
int totalIntensity = 0;
for (Map.Entry<Pair<Integer, Integer>, List<Line>> entry : stars.entrySet()) {
if (entry.getValue().size() / 2 == K) {
List<Integer> intensities = new ArrayList<>();
for (Line line : entry.getValue()) {
intensities.add(countCells(line, entry.getKey(), true));
}
totalIntensity += Collections.min(intensities);
}
}
System.out.println(totalIntensity);
}
// Pair class to store x and y coordinates of intersections
static class Pair<T, U> {
T first;
U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public void set(T first, U second) {
this.first = first;
this.second = second;
}
}
}



Comments