Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save madsunrise/baa12f9c70c74973632b318bfcb4dafe to your computer and use it in GitHub Desktop.
Save madsunrise/baa12f9c70c74973632b318bfcb4dafe to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int width = scanner.nextInt();
int height = scanner.nextInt();
OurAdvert ourAdvert = new OurAdvert(
scanner.nextInt(),
scanner.nextInt()
);
int advertCount = scanner.nextInt();
List<Area> advertList = new ArrayList<>(advertCount);
for (int i = 0; i < advertCount; ++i) {
Area advert = new Area(
scanner.nextInt(),
scanner.nextInt(),
scanner.nextInt(),
scanner.nextInt()
);
advertList.add(advert);
}
Area result = findResult(width, height, ourAdvert, advertList);
System.out.println(result.x1 + " " + result.y1 + " " + result.x2 + " " + result.y2);
}
private static Area findResult(int width, int height, OurAdvert ourAdvert, List<Area> adverts) {
int maxRow = height - ourAdvert.height + 1;
int maxCol = width - ourAdvert.width + 1;
for (int row = 0; row < maxRow; row++) {
for (int col = 0; col < maxCol; ) {
CheckResult result = checkThisCase(row, col, adverts, ourAdvert);
if (result.answer != null) {
return result.answer;
}
col += result.canStepByX;
}
}
throw new RuntimeException();
}
private static class CheckResult {
final Area answer;
final int canStepByX;
public CheckResult(Area answer, int canStepByX) {
this.answer = answer;
this.canStepByX = canStepByX;
}
}
private static CheckResult checkThisCase(int rowIdx, int colIdx, List<Area> adverts, OurAdvert ourAdvert) {
int x1 = colIdx;
int y1 = rowIdx;
int x2 = colIdx + ourAdvert.width;
int y2 = rowIdx + ourAdvert.height;
int canSkipByX = 0;
for (Area advert : adverts) {
if (advert.hasIntersectionWith(x1, y1, x2, y2)) {
canSkipByX = Math.max(canSkipByX, advert.x2 - colIdx);
}
}
if (canSkipByX == 0) {
return new CheckResult(new Area(x1, y1, x2, y2), 0);
}
return new CheckResult(null, canSkipByX);
}
private static class OurAdvert {
final int width;
final int height;
public OurAdvert(int width, int height) {
this.width = width;
this.height = height;
}
}
private static class Area {
private final int x1;
private final int y1;
private final int x2;
private final int y2;
public Area(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public boolean hasIntersectionWith(int x1, int y1, int x2, int y2) {
if (this.x1 >= x2 || this.x2 <= x1) {
return false;
}
return this.y1 < y2 && this.y2 > y1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment