Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

30-Dolchae #112

Merged
merged 1 commit into from
Feb 26, 2024
Merged

30-Dolchae #112

merged 1 commit into from
Feb 26, 2024

Conversation

Dolchae
Copy link
Collaborator

@Dolchae Dolchae commented Feb 22, 2024

πŸ”— 문제 링크

2644 μ΄Œμˆ˜κ³„μ‚°

βœ”οΈ μ†Œμš”λœ μ‹œκ°„

1μ‹œκ°„

✨ μˆ˜λ„ μ½”λ“œ

문제

주어진 두 μ‚¬λžŒμ˜ 촌수λ₯Ό κ³„μ‚°ν•˜λŠ” λ¬Έμ œμ΄λ‹€.

  • λΆ€λͺ¨μ™€ μžμ‹ 사이가 1촌으둜 μ •μ˜λ˜λ―€λ‘œ λ‚˜μ™€ ν• μ•„λ²„μ§€λŠ” 2촌, 아버지 ν˜•μ œλ“€κ³Ό ν• μ•„λ²„μ§€λŠ” 1촌, λ‚˜μ™€ 아버지 ν˜•μ œλ“€μ€ 3촌이 λœλ‹€.
    μž…λ ₯
  • 첫째 쀄에 전체 μ‚¬λžŒ 수, λ‘˜μ§Έ 쀄에 촌수λ₯Ό 계산해야 ν•˜λŠ” 두 μ‚¬λžŒμ˜ 번호(a,b), μ…‹μ§Έ 쀄에 κ΄€κ³„μ˜ 수 m, λ„·μ§Έ μ€„λΆ€ν„°λŠ” λΆ€λͺ¨ μžμ‹ κ°„μ˜ 관계 두 번호 x,yκ°€ λ‚˜μ˜¨λ‹€.
    • μ΄λ•Œ xκ°€ y의 λΆ€λͺ¨κ°€ λœλ‹€.
      좜λ ₯
  • a,b의 촌수λ₯Ό 계산해 좜λ ₯ν•˜λ©΄ λ˜λŠ”λ°, μΉœμ²™ 관계가 μ „ν˜€ 없을 κ²½μš°μ—λŠ” -1을 좜λ ₯ν•œλ‹€.

예제 1)
image
image


μ½”λ“œ

n = int(input())
a,b = map(int, input().split())
node_num = int(input())
graph = [[] for _ in range(n+1)]
visited = [False] * (n+1)
result = []
  • 첫째 쀄에 전체 μ‚¬λžŒ 수(n), λ‘˜μ§Έ 쀄에 촌수λ₯Ό 계산해야 ν•˜λŠ” 두 μ‚¬λžŒμ˜ 번호(a,b), μ…‹μ§Έ 쀄에 κ΄€κ³„μ˜ 수(node_num)λ₯Ό μž…λ ₯λ°›λŠ”λ‹€.
  • 관계듀을 μ €μž₯ν•  graph 2차원 λ°°μ—΄κ³Ό λ°©λ¬Έ μ—¬λΆ€λ₯Ό 확인할 visited, κ²°κ³Όλ₯Ό μ €μž₯ν•  result 리슀트λ₯Ό μ„ μ–Έν•œλ‹€.

for _ in range(node_num):
  x, y = map(int, input().split())
  graph[x].append(y)
  graph[y].append(x)
  • κ΄€κ³„μ˜ 수만큼 for문을 λ°˜λ³΅ν•˜λ©° x와 yλ₯Ό μž…λ ₯λ°›μœΌλ©° 연결정보λ₯Ό graph에 μ €μž₯ν•œλ‹€.

def dfs(v, num):
  num += 1
  visited[v] = True

  if v == b:
    result.append(num)

  for i in graph[v]:
    if not visited[i]:
      dfs(i, num)

aμ—μ„œ b둜 κ°€λŠ” dfsλ₯Ό μˆ˜ν–‰ν•œλ‹€.

  • ν˜„μž¬ λ…Έλ“œ v와 ν˜„μž¬κΉŒμ§€μ˜ 거리 num을 λ°›λŠ”λ‹€.
  • λ°©λ¬Έ λ…Έλ“œλ₯Ό μ²΄ν¬ν•˜κ³  λ§Œμ•½ b에 λ„λ‹¬ν–ˆλ‹€λ©΄ ν•΄λ‹Ή 경둜의 길이 num을 μΆ”κ°€ν•œλ‹€.
  • λ°©λ¬Έν•˜μ§€ μ•Šμ€ λ…Έλ“œλ“€μ„ 계속 μž¬κ·€μ μœΌλ‘œ νƒμƒ‰ν•œλ‹€.

dfs(a, 0)
if len(result) == 0:
  print(-1)
else:
  print(result[0]-1)
  • λ§Œμ•½ resultκ°€ λΉ„μ–΄μžˆλ‹€λ©΄ a와 b 두 μ‚¬λžŒμ˜ μΉœμ²™ 관계가 μ—†λ‹€λŠ” λœ»μ΄λ―€λ‘œ -1을 좜λ ₯ν•œλ‹€.
  • 그렇지 μ•Šλ‹€λ©΄ 졜초의 경둜의 κΈΈμ΄μ—μ„œ (좜발 λ…Έλ“œλ₯Ό μ œμ™Έν•˜κΈ° μœ„ν•΄) 1을 λΊ€ 값을 좜λ ₯ν•œλ‹€.


전체 μ½”λ“œ

n = int(input())
a,b = map(int, input().split())
node_num = int(input())
graph = [[] for _ in range(n+1)]
visited = [False] * (n+1)
result = []

for _ in range(node_num):
  x, y = map(int, input().split())
  graph[x].append(y)
  graph[y].append(x)

def dfs(v, num):
  num += 1
  visited[v] = True

  if v == b:
    result.append(num)

  for i in graph[v]:
    if not visited[i]:
      dfs(i, num)

dfs(a, 0)
if len(result) == 0:
  print(-1)
else:
  print(result[0]-1)

πŸ“š μƒˆλ‘­κ²Œ μ•Œκ²Œλœ λ‚΄μš©

ꡬꡐ황 μ„ λ°°λ‹˜μ΄ μΆ”μ²œν•΄μ£Όμ‹  λ°±νŠΈλž˜ν‚Ή 문제λ₯Ό 풀어보렀 ν–ˆλŠ”λ° μ°Ύμ•„λ³΄λ‹ˆ λ°±νŠΈλž˜ν‚Ήμ— DFSκ°€ μ“°μΈλ‹€κΈΈλž˜ DFS 문제λ₯Ό λ¨Όμ € λ„μ „ν•΄λ³΄μ•˜λ‹€. 그런데 μ˜€λžœλ§Œμ— ν‘Έλ‹ˆ λ”λ”μš± λͺ¨λ₯΄κ² μ–΄μ„œ μ• λ¨Ήλ‹€κ°€ κ²°κ΅­ λΈ”λ‘œκ·Έ μ°Έκ³ ν–ˆλ‹€..


μ½”λ“œ μ°Έκ³  λΈ”λ‘œκ·Έ

Copy link
Member

@xxubin04 xxubin04 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DFS둜 ν‘Έλ‹ˆκΉŒ κ°„κ²°ν•˜κ²Œ μ½”λ“œκ°€ μ§œμ§€λŠ”κ΅°μš”...πŸ˜‚
μ €λŠ” BFS둜 λ„μ „ν–ˆλŠ”λ° μ½”λ“œκ°€ 1000Bκ°€ λ„˜μ—ˆλ„€μš”...ν•˜ν•˜
κΉ”λ”ν•˜κ²Œ 잘 ν‘Έμ…”μ„œ 제 μ½”λ“œλ§Œ 남기고 κ°€κ² μŠ΅λ‹ˆλ‹€!

BFS μ½”λ“œ
from collections import deque
input = open(0).readline

people_num = int(input())
A, B = map(int, input().split())
relationship = [[0] for _ in range(people_num + 1)]

for i in range(relation_num := int(input())):
    a, b = map(int, input().split())
    if relationship[a] == [0]:
        relationship[a] = [b]
    else:
        relationship[a].append(b)
    
    if relationship[b] == [0]:
        relationship[b] = [a]
    else:
        relationship[b].append(a)

visited = [0 for _ in range(people_num + 1)]

def chon(r, c, p):
    global ans, check
    q = deque()
    q.append((r, c, p))
    while q:
        relation, cnt, person = q.popleft()
        if visited[person] == 0:
            visited[person] = 1
            cnt += 1
            for j in relation[person]:
                if j == A:
                    ans.append(cnt)
                    return ans
                q.append((relation, cnt, j))

ans = []       
cnt = 0
answer = chon(relationship, cnt, B)
print(min(answer) if answer else -1)

@Dolchae Dolchae removed the request for review from gjsk132 February 24, 2024 11:05
Copy link
Collaborator

@9kyo-hwang 9kyo-hwang left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

μ €λŠ” μ•„μ˜ˆ λͺ¨λ“  λ…Έλ“œμ— λŒ€ν•œ 거리 정보λ₯Ό κΈ°λ‘ν•˜λŠ” 리슀트λ₯Ό ν•˜λ‚˜ λ§Œλ“€μ–΄μ„œ, κ·Έ 값을 계속 λ°”κΏ”μ£ΌλŠ” μ‹μœΌλ‘œ μ§œλ΄€λ„€μš”.

input = open(0).readline

n = int(input())
a, b = map(int, input().split())
m = int(input())

tree = [[] for _ in range(n + 1)]
dists = [-1] * (n + 1)  # μ΄ˆκΈ°κ°’μ€ -1
dists[a] = 0  # μ‹œμž‘ λ…Έλ“œμΈ aλŠ” 거리 0으둜 μ„€μ •

for _ in range(m):
    x, y = map(int, input().split())
    tree[x].append(y)
    tree[y].append(x)
    

def dfs(src: int = a):
    for dst in tree[src]:  # src와 μ—°κ²°λœ 인접 λ…Έλ“œμ— λŒ€ν•΄
        if dists[dst] == -1:  # μ΄ˆκΈ°κ°’(-1) κ·ΈλŒ€λ‘œλΌλ©΄ λ°©λ¬Έν•œ 적 μ—†μŒ
            dists[dst] = dists[src] + 1  # src λ…Έλ“œκΉŒμ§€μ˜ 거리 + 1둜 μž¬μ„€μ •
            dfs(dst)  # μž¬κ·€ 호좜
        
dfs()
print(dists[b])  # μ΅œμ’…μ μœΌλ‘œ b에 λŒ€ν•œ 거리값을 좜λ ₯ν•˜λ©΄ 됨. λ„λ‹¬ν–ˆμœΌλ©΄ 거리값이, 도달λͺ»ν–ˆμœΌλ©΄ 초기 -1값이 κ·ΈλŒ€λ‘œ λ‹΄κ²¨μ ΈμžˆμŒ

그리고 λ°˜λ“œμ‹œ μž¬κ·€λ‘œ ν•  ν•„μš”λ„ μ—†κ² μ£ ? stack을 μ΄μš©ν•œ dfs도 κ°€λŠ₯ν•˜λ‹΅λ‹ˆλ‹€.

input = open(0).readline

n = int(input())
a, b = map(int, input().split())
m = int(input())

tree = [[] for _ in range(n + 1)]
dists = [-1] * (n + 1)
dists[a] = 0

for _ in range(m):
    x, y = map(int, input().split())
    tree[x].append(y)
    tree[y].append(x)
    

stack = [a]
while stack:
    src = stack.pop()
    if src == b:
        break
        
    for dst in tree[src]:
        if dists[dst] == -1:
            dists[dst] = dists[src] + 1
            stack.append(dst)


print(dists[b])

마치 queueλ₯Ό μ“΄ bfsλž‘ μ½”λ“œκ°€ λΉ„μŠ·ν•˜μ£ ? μ•„λž˜κ°€ bfs μ½”λ“œμž…λ‹ˆλ‹€.

from collections import deque
input = open(0).readline

n = int(input())
a, b = map(int, input().split())
m = int(input())

tree = [[] for _ in range(n + 1)]
dists = [-1] * (n + 1)
dists[a] = 0

for _ in range(m):
    x, y = map(int, input().split())
    tree[x].append(y)
    tree[y].append(x)


q = deque([a])
while q:
    src = q.popleft()
    if src == b:
        break
    
    for dst in tree[src]:
        if dists[dst] == -1:
            dists[dst] = dists[src] + 1
            q.append(dst)


print(dists[b])

νŠΉμ΄ν•˜κ²Œ 이 λ¬Έμ œλŠ” bfsκ°€ 속도가 제일 λŠλ¦¬λ„€μš”
image
맨 밑이 μž¬κ·€ν˜ΈμΆœ, κ°€μš΄λ°κ°€ stack dfs, 맨 μœ„κ°€ queue bfs μ½”λ“œμž…λ‹ˆλ‹€.

Comment on lines +13 to +22
def dfs(v, num):
num += 1
visited[v] = True

if v == b:
result.append(num)

for i in graph[v]:
if not visited[i]:
dfs(i, num)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

거리값(촌 수)을 num이 κΈ°μ–΅ν•˜κ³  μžˆμœΌλ‹ˆ, 이λ₯Ό λ°˜ν™˜ν•˜λŠ” μ‹μœΌλ‘œ μ½”λ“œλ₯Ό 짜면 μ’€ 더 직관적일 것 κ°™λ„€μš”.

def dfs(src: int = a, dist: int = 0):  # λ””ν΄νŠΈ νŒŒλΌλ―Έν„°λ‘œ λ…Έλ“œ a, 거리 0을 지정함
    if visited[src]:  # λ°©λ¬Έν–ˆλ˜ 정점이라면
        return -1  # μ°ΎλŠ” λŒ€μƒμ΄ μ•„λ‹ˆλ―€λ‘œ -1 리턴
    elif src == b:  # ν˜„μž¬ κ²€μ‚¬ν•˜λŠ” λ…Έλ“œκ°€ μ°ΎλŠ” λŒ€μƒ(b)이라면
        return dist  # ν˜„μž¬κΉŒμ§€μ˜ 거리값을 λ°˜ν™˜
    else: 
        visited[src] = True  # 방문처리
        ans = -1
        for dst in tree[src]:  # μΈμ ‘ν•œ λ…Έλ“œλ“€μ— λŒ€ν•΄
            ans = max(ans, dfs(dst, dist + 1))  # μž¬κ·€ ν˜ΈμΆœμ— λŒ€ν•œ κ²°κ³Ό 쀑 큰 값을 취함
        return ans  # 큰 값은 μ‹€μ œ 거리일 κ±°κ³ , μ•„λ‹ˆλΌλ©΄ λͺ»μ°Ύμ•˜λ‹€λŠ” 의미의 -1이 λ‹΄κ²¨μžˆμŒ

이런 μ‹μœΌλ‘œ μž‘μ„±ν•˜λ©΄, dfs ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν–ˆμ„ λ•Œ μ‹€μ œ 거리 κ°’ 이 λ°˜ν™˜λ˜κ±°λ‚˜ λͺ»μ°Ύμ•˜λ‹€λŠ” λœ»μ—μ„œ -1 이 λ°˜ν™˜λ˜κ² μ£ ?
κ·Έκ±°λ₯Ό λ°”λ‘œ 좜λ ₯ν•΄μ£Όλ©΄ λ©λ‹ˆλ‹€.

print(dfs())  # dfs ν•¨μˆ˜μ— λ””ν΄νŠΈ νŒŒλΌλ―Έν„°λ₯Ό μ§€μ •ν•΄λ†”μ„œ 인자λ₯Ό λ„˜κ²¨μ£Όμ§€ μ•Šμ•„λ„ λ©λ‹ˆλ‹€.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants