본문 바로가기

PS/boj

[BOJ] 10497 Hitting the Targets

문제 링크

www.acmicpc.net/problem/10497

풀이

쿼리로 들어오는 좌표를 다른 모든 네모와 원에 대해 포함관계를 확인하면서 카운팅하면 된다.

Java 코드

더보기

코딩하다 보니까 나도 모르게 객체지향적으로 짜고 있는 나를 발견했다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

interface Shape {
    boolean contains(int x, int y);
}

class Rectangle implements Shape {
    public int x1, y1;
    public int x2, y2;

    public Rectangle(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    @Override
    public boolean contains(int x, int y) {
        return x1 <= x && x <= x2 && y1 <= y && y <= y2;
    }
}

class Circle implements Shape {
    public int x, y, r;

    public Circle(int x, int y, int r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }

    @Override
    public boolean contains(int x, int y) {
        int r = (this.x - x) * (this.x - x) + (this.y - y) * (this.y - y);
        return r <= this.r * this.r;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder out = new StringBuilder();

        int m = Integer.parseInt(in.readLine());
        List<Shape> shapes = new ArrayList<>();

        for (int i = 0; i < m; ++i) {
            StringTokenizer st = new StringTokenizer(in.readLine());
            if ("rectangle".equals(st.nextToken())) {
                int x1 = Integer.parseInt(st.nextToken());
                int y1 = Integer.parseInt(st.nextToken());
                int x2 = Integer.parseInt(st.nextToken());
                int y2 = Integer.parseInt(st.nextToken());
                shapes.add(new Rectangle(x1, y1, x2, y2));
            } else {
                int x = Integer.parseInt(st.nextToken());
                int y = Integer.parseInt(st.nextToken());
                int r = Integer.parseInt(st.nextToken());
                shapes.add(new Circle(x, y, r));
            }
        }

        int n = Integer.parseInt(in.readLine());
        while (n-- > 0) {
            StringTokenizer st = new StringTokenizer(in.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());

            int cnt = 0;
            for (Shape shape : shapes) if (shape.contains(x, y)) ++cnt;

            out.append(cnt).append('\n');
        }

        System.out.println(out);
    }
}

'PS > boj' 카테고리의 다른 글

[BOJ] 17211 좋은 날 싫은 날  (0) 2021.02.15
[BOJ] 16952 체스판 여행 2  (0) 2021.02.09
[BOJ] 15487 A[j]-A[i]+A[l]-A[k]  (0) 2021.02.03
[BOJ] 14006 Large Ping Pong Tournament  (0) 2021.02.03
[BOJ] 16265 Spreadsheets  (0) 2021.02.03