๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 14588 - Line Friends (Small)

by HandHand 2021. 3. 14.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 14588๋ฒˆ

ํ’€์ด ๊ณผ์ •

์„ ๋ถ„์˜ ๊ฒน์นฉ ์œ ๋ฌด๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ ์„ ๋ถ„๊ฐ„์˜ ์ตœ์†Œ ๊ฑฐ๋ฆฌ ๊ฐ’์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ชจ๋“  ์„ ๋ถ„๊ฐ„์˜ ์ตœ์†Œ ๊ฑฐ๋ฆฌ ์ •๋ณด๋ฅผ ์•Œ์•„์•ผํ•˜๊ณ  N ์ด ์ตœ๋Œ€ 300 ์ด๊ธฐ ๋•Œ๋ฌธ์— ํ”Œ๋กœ์ด๋“œ ์™€์ƒฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ณ  ์„ ๋ถ„ ๊ฒน์นฉ ์—ฐ์‚ฐ๊ณผ ๊ด€๋ จํ•ด์„œ ๋‹ค๋ฅธ ๋ถ„์˜ ์ œ์ถœ ์ฝ”๋“œ๋ฅผ ํ™•์ธํ•ด๋ดค๋Š”๋ฐ
๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ข‹์€ ๋ฐฉ๋ฒ•๋„ ์žˆ๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

a1, b1 = ์„ ๋ถ„ 1 ์–‘ ๋์ 
a2, b2 = ์„ ๋ถ„ 2 ์–‘ ๋์ 
if max(a1, a2) <= min(b1, b2):
    # ๋‘ ์„ ๋ถ„ ๊ฒน์นจ

์œ„ ์ฝ”๋“œ๋Š” ๋‘ ์„ ๋ถ„๊ฐ™์˜ ๋ ์ ์„ ์ด์šฉํ•ด์„œ max, min ์„ ๊ณ„์‚ฐํ•˜๊ณ  ์ด๋ฅผ ๋น„๊ตํ•˜์—ฌ ๊ฒน์นจ ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•˜๋Š” ์˜์‚ฌ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.
์ดํ›„์— ์ด์™€ ์œ ์‚ฌํ•˜๊ฒŒ ์„ ๋ถ„ ๊ฒน์นจ ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•ด์•ผ ํ•  ๋•Œ ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๐Ÿ˜„

์ฝ”๋“œ


import sys

N = int(input())
lines = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
Q = int(input())
questions = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]


def check_overlap(pivot, opponent):
    if opponent[0] > pivot[1]:
        return False
    elif opponent[1] < pivot[0]:
        return False

    return True


def make_graph():
    dist = [[sys.maxsize] * N for _ in range(N)]

    for (p_idx, pivot) in enumerate(lines):
        for (o_idx, opponent) in enumerate(lines):
            if p_idx != o_idx and check_overlap(pivot, opponent):
                dist[p_idx][o_idx] = 1

    return dist


def floyd(dist):
    for v in range(N):
        dist[v][v] = 0

    for k in range(N):
        for u in range(N):
            for v in range(N):
                dist[u][v] = min(dist[u][v], dist[u][k] + dist[k][v])


def solution():
    dist = make_graph()
    floyd(dist)

    for frm, to in questions:
        cost = dist[frm - 1][to - 1]
        answer = cost if cost != sys.maxsize else -1
        print(answer)


solution()
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 17521 - Byte Coin  (0) 2021.03.14
BOJ 20363 - ๋‹น๊ทผ ํ‚ค์šฐ๊ธฐ  (0) 2021.03.14
BOJ 14925 - ๋ชฉ์žฅ ๊ฑด์„คํ•˜๊ธฐ  (0) 2021.03.14
BOJ 13164 - ํ–‰๋ณต ์œ ์น˜์›  (0) 2021.03.14
BOJ 3109 - ๋นต์ง‘  (0) 2021.03.14

๐Ÿ’ฌ ๋Œ“๊ธ€