ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 17839 Baba is Rabbit with Python
    PS 2022. 5. 13. 15:55
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 17839 Baba is Rabbit

    ๐Ÿ’ก ์กฐ๊ฑด

    1. N(1 โ‰ค N โ‰ค 100,000)

    2. N๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๋ช…๋ น์ด ์ฃผ์–ด์ง„๋‹ค.
      ๊ฐ ๋ช…๋ น์€ p is q์˜ ํ˜•ํƒœ๋กœ ์ฃผ์–ด์ง€๋ฉฐ, p์™€ q๋Š” ์ฒซ ๊ธ€์ž๊ฐ€ ์˜๋ฌธ ๋Œ€๋ฌธ์ž์ด๊ณ , ๋‚˜๋จธ์ง€ ๊ธ€์ž๋Š” ์˜๋ฌธ ์†Œ๋ฌธ์ž์ธ ๊ธธ์ด 10 ์ด๋‚ด์˜ ๋ฌธ์ž์—ด์ด๋‹ค.

    3. Baba์— ๋ช…๋ น์„ ํ•œ ๋ฒˆ ์ด์ƒ ์ ์šฉํ•œ ๊ฒฐ๊ณผ๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋ฌผ์„ ์‚ฌ์ „์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค.
      ๋‹จ, ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ช…๋ น์ด ์—†๋‹ค๋ฉด, ์•„๋ฌด๊ฒƒ๋„ ์ถœ๋ ฅํ•˜์ง€ ์•Š๋Š”๋‹ค.

    4. ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰, BFS ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from collections import deque
    from sys import stdin
    
    graph = {}
    for _ in range(int(stdin.readline())):
        a, b = stdin.readline().rstrip().split(' is ')
    
        if a not in graph:
            graph[a] = [b]
        else:
            graph[a].append(b)
    
    
    def solve():
        q = deque()
        q.append("Baba")
        visited = {}
        while q:
            now = q.popleft()
            try:
                for i in graph[now]:
                    if i not in visited:
                        visited[i] = 1
                        q.append(i)
            except:
                pass
    
        return visited
    
    
    try:
        ans = sorted(solve())
        print(*ans, sep='\n')
    
    except:
        pass

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ 1

    1
    Rabbit is Carrot

    ์‹คํ–‰๊ฒฐ๊ณผ 1

    ์˜ˆ์ œ 2

    3
    Rabbit is Carrot
    Baba is Cat
    Cat is Rabbit

    ์‹คํ–‰๊ฒฐ๊ณผ 2

    Carrot
    Cat
    Rabbit

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. Baba์— ๋ช…๋ น์„ ํ•œ ๋ฒˆ ์ด์ƒ ์ ์šฉํ•œ ๊ฒฐ๊ณผ๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋ฝ‘์•„์•ผํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

    2. ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰์„ ํ•ด์•ผํ•˜๋Š”๋ฐ, ๋ฌธ์ž์—ด๋กœ ์ด๋ฃจ์–ด์ง„ ๋…ธ๋“œ๋กœ ๊ตฌ์„ฑ๋œ ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋”•์…”๋„ˆ๋ฆฌ ํƒ€์ž…์„ ์‚ฌ์šฉํ•ด ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.
      ์–ด๋–ค ์‚ฌ๋ฌผ p์— ๋ช…๋ น์„ ํ•œ ๋ฒˆ ์ด์ƒ ์ ์šฉํ•œ ๊ฒฐ๊ณผ๋กœ ๋‹ค์‹œ p๊ฐ€ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ์—†๋‹ค. ๋ผ๋Š” ์กฐ๊ฑด์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹จ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋ฉด ๋œ๋‹ค.

    3. ๋งŒ๋“  ๊ทธ๋ž˜ํ”„๋ฅผ BFS ๋กœ ํƒ์ƒ‰ํ•˜๋ฉด ๋˜๋Š”๋ฐ, Baba ์— ๋ช…๋ น์„ ํ•œ ๋ฒˆ ์ด์ƒ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ์—๋Š” Baba๋ฅผ ๋„ฃ์–ด ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•œ๋‹ค.

    4. ๋”•์…”๋„ˆ๋ฆฌ์— ํ•ด๋‹น ํ‚ค๊ฐ€ ์—†์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— try - except ๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค€๋‹ค.

    ๐Ÿ’พ ๋ฐฐ์šด์ 

    1. ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž์—ด๋กœ ์ด๋ฃจ์–ด์ง„ ๊ทธ๋ž˜ํ”„๋ฅผ ๋งŒ๋“ค๊ณ , ํƒ์ƒ‰ํ•˜๋Š” ๋ฒ•
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.