Notice
Recent Posts
문제 풀이 및 개발 공간
[백준] 20040번 사이클 게임 (gold 4 본문
import java.io.*;
import java.util.*;
public class Main{
static int[] num;
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st=new StringTokenizer(br.readLine());
int n=Integer.valueOf(st.nextToken());
int m=Integer.valueOf(st.nextToken());
num=new int[n+1];
for(int i=1; i<=n; i++){
num[i]=i;
}
int answer=0;
for(int i=0; i<m; i++){
st=new StringTokenizer(br.readLine());
int a=Integer.valueOf(st.nextToken());
int b=Integer.valueOf(st.nextToken());
int fa=Find(a);
int fb=Find(b);
if(fa!=fb){
Union(a,b);
}
else{
answer=i+1;
break;
}
}
bw.write(answer+"");
bw.flush();
}
public static int Find(int v){
if(num[v]==v){
return v;
}
else{
return num[v]=Find(num[v]);
}
}
public static void Union(int a,int b){
int fa=Find(a);
int fb=Find(b);
if(fa!=fb){
num[fa]=fb;
}
}
}
//union-find문제를 사용하는 간단한 문제.
//여기서 중요한 부분을 알게되었다. 백준의 입력을 만약 답이 나온상황이면 break를 쓰고
//더이상 받지 않아도 된다는 것이다.
//실제로 다 받는 코드가 30~40%정도 느렸다.
'백준공부 > java' 카테고리의 다른 글
[백준] 20303번 할로윈의 양아치 (gold 3 (0) | 2024.03.25 |
---|---|
[백준] 1261번 알고스팟 (gold 4 (0) | 2024.03.25 |
[백준] 2580번 스도쿠 (gold 4 (0) | 2024.03.24 |
[백준] 2239번 스도쿠 (gold 4 (0) | 2024.03.24 |
[백준] 22233번 가희와 키워드 (silver 2 (0) | 2024.03.22 |