File tree Expand file tree Collapse file tree 4 files changed +102
-0
lines changed
Expand file tree Collapse file tree 4 files changed +102
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+
3+ read = lambda : sys .stdin .readline ().rstrip ()
4+
5+
6+ class Problem :
7+ def __init__ (self ):
8+ self .n , self .m = map (int , read ().split ())
9+ self .data = [tuple (map (int , read ().split ())) for _ in range (self .m )]
10+ self .parent = list (range (self .n ))
11+
12+ def solve (self ) -> None :
13+ count = 0
14+ for idx , (x , y ) in enumerate (self .data ):
15+ if self .find_cycle (x , y ):
16+ count = idx + 1
17+ break
18+
19+ print (count )
20+
21+ def find_cycle (self , x : int , y : int ) -> bool :
22+ root_x , root_y = self .find_root (x ), self .find_root (y )
23+ if root_x == root_y :
24+ return True
25+
26+ self .parent [root_y ] = root_x
27+ return False
28+
29+ def find_root (self , x : int ) -> int :
30+ while self .parent [x ] != x :
31+ self .parent [x ] = self .parent [self .parent [x ]]
32+ x = self .parent [x ]
33+
34+ return x
35+
36+
37+ if __name__ == "__main__" :
38+ Problem ().solve ()
Original file line number Diff line number Diff line change 1+ [
2+ {
3+ "input" : [
4+ " 6 5" ,
5+ " 0 1" ,
6+ " 1 2" ,
7+ " 2 3" ,
8+ " 5 4" ,
9+ " 0 4"
10+ ],
11+ "expected" : [
12+ " 0"
13+ ]
14+ },
15+ {
16+ "input" : [
17+ " 6 5" ,
18+ " 0 1" ,
19+ " 1 2" ,
20+ " 1 3" ,
21+ " 0 3" ,
22+ " 4 5"
23+ ],
24+ "expected" : [
25+ " 4"
26+ ]
27+ }
28+ ]
Original file line number Diff line number Diff line change 1+ import json
2+ import os .path
3+ import unittest
4+ from io import StringIO
5+ from unittest .mock import patch
6+
7+ from parameterized import parameterized
8+
9+ from main import Problem
10+
11+
12+ def load_sample (filename : str ):
13+ path = os .path .join (os .path .dirname (os .path .abspath (__file__ )), filename )
14+
15+ with open (path , "r" ) as file :
16+ return [(case ["input" ], case ["expected" ]) for case in json .load (file )]
17+
18+
19+ class TestCase (unittest .TestCase ):
20+ @parameterized .expand (load_sample ("sample.json" ))
21+ def test_case (self , case : str , expected : list [str ]):
22+ # When
23+ with (
24+ patch ("sys.stdin.readline" , side_effect = case ),
25+ patch ("sys.stdout" , new_callable = StringIO ) as output ,
26+ ):
27+ Problem ().solve ()
28+
29+ result = output .getvalue ().rstrip ()
30+
31+ # Then
32+ self .assertEqual ("\n " .join (expected ), result )
33+
34+
35+ if __name__ == "__main__" :
36+ unittest .main ()
You can’t perform that action at this time.
0 commit comments