[Link] https://www.acmicpc.net/problem/20040
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
String[] line = getLine();
// StringBuilder sb = new StringBuilder();
int n = toi(line[0]), m = toi(line[1]);
int[] union = new int[n];
for(int i = 0; i < n; i++) union[i] = i;
for(int i = 0; i < m; i++) {
line = getLine();
int v1 = toi(line[0]), v2 = toi(line[1]);
int p1 = getParent(union, v1), p2 = getParent(union, v2);
if(p1 == p2) {
print(i + 1);
return;
}
if(p1 < p2) union[p2] = p1;
else union[p1] = p2;
}
print(0);
}
static int getParent(int[] union, int idx) {
if(union[idx] == idx) return idx;
return union[idx] = getParent(union, union[idx]);
}
static int sum(int[] arr, int s, int e) { int sum = 0; for(int i = s; i <= e; i++) sum+=arr[i]; return sum; }
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static <T> void print(T s) { System.out.print(s); }
}