Skip to content

Commit

Permalink
백준 20040번 사이클 게임
Browse files Browse the repository at this point in the history
  • Loading branch information
skysign committed Nov 2, 2024
1 parent 7c0f0e8 commit f10b93d
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 0 deletions.
44 changes: 44 additions & 0 deletions 백준 20040번 사이클 게임/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import copy
import sys
from collections import deque

# 문제를 BFS로 풀수 없는 반례
# 3 3
# 0 1
# 1 2
# 1 2
# 즉, 마지막 edge가 cycle을 만드는 경우는 BFS로 구현하면, 알 수 없음

def solve():
N, M = map(int, sys.stdin.readline().strip().split())
vertexes = [n for n in range(N)]

for m in range(M):
v1, v2 = map(int, sys.stdin.readline().strip().split())

root_v1 = find(v1, vertexes)
root_v2 = find(v2, vertexes)

if root_v1 == root_v2:
print(m + 1)
return
else:
union(root_v1, root_v2, vertexes)

print(0)


def union(v1, v2, vertexes):
vertexes[max(v1, v2)] = min(v1, v2)


def find(v, vertexes):
if v != vertexes[v]:
vertexes[v] = find(vertexes[v], vertexes)
return vertexes[v]

return vertexes[v]


if __name__ == '__main__':
solve()
6 changes: 6 additions & 0 deletions 백준 20040번 사이클 게임/test1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
6 5
0 1
1 2
2 3
5 4
0 4
1 change: 1 addition & 0 deletions 백준 20040번 사이클 게임/test1_answer.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0
6 changes: 6 additions & 0 deletions 백준 20040번 사이클 게임/test2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
6 5
0 1
1 2
1 3
0 3
4 5
1 change: 1 addition & 0 deletions 백준 20040번 사이클 게임/test2_answer.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4
6 changes: 6 additions & 0 deletions 백준 20040번 사이클 게임/test3.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
6 5
0 1
2 1
3 1
4 1
4 0
1 change: 1 addition & 0 deletions 백준 20040번 사이클 게임/test3_answer.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
5
30 changes: 30 additions & 0 deletions 백준 20040번 사이클 게임/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import sys
from pathlib import Path
from unittest import TestCase
from main import solve


class Test(TestCase):
def my_solve(self, testcase_input):
sys.stdin = open(testcase_input, 'r')
stdout = sys.stdout
sys.stdout = open('stdout.txt', 'w')
solve()
sys.stdout.close()
sys.stdout = stdout

def test_solve(self, testcase_number: str):
self.my_solve('test' + testcase_number + '.txt')
self.assertEqual(
Path('test' + testcase_number + '_answer.txt').read_text().strip(),
Path('stdout.txt').read_text().strip())

def test1_solve(self):
self.test_solve('1')

def test2_solve(self):
self.test_solve('2')

# 출처: https://www.acmicpc.net/board/view/106868
def test2_solve(self):
self.test_solve('3')

0 comments on commit f10b93d

Please sign in to comment.