File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+
5+ public class Main {
6+ static int N ;
7+ static List<Integer > [] graph;
8+ static int [] parents;
9+ public static void main (String [] args ) throws IOException {
10+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
11+ N = Integer . parseInt(br. readLine());
12+ graph = new List [N + 1 ];
13+ for (int i = 1 ; i <= N ; i++ ) {
14+ graph[i] = new ArrayList<> ();
15+ }
16+ makeParents();
17+ for (int i = 0 ; i < N - 2 ; i++ ) {
18+ StringTokenizer st = new StringTokenizer (br. readLine());
19+ int a = Integer . parseInt(st. nextToken());
20+ int b = Integer . parseInt(st. nextToken());
21+ graph[a]. add(b);
22+ graph[b]. add(a);
23+ union(a, b);
24+ }
25+ boolean found = false ;
26+ for (int i = 1 ; i < N ; i++ ) {
27+ if (found) break ;
28+ for (int j = i + 1 ; j <= N ; j++ ) {
29+ if (find(i) == find(j)) {
30+ continue ;
31+ }
32+ System . out. println(i + " " + j);
33+ found = true ;
34+ break ;
35+ }
36+ }
37+ br. close();
38+
39+ }
40+
41+ static void makeParents () {
42+ parents = new int [N + 1 ];
43+ for (int i = 1 ; i <= N ; i++ ) {
44+ parents[i] = i;
45+ }
46+ }
47+
48+ static int find (int a ) {
49+ if (parents[a] == a) {return a;}
50+ return parents[a] = find(parents[a]);
51+ }
52+
53+ static boolean union (int a , int b ) {
54+ int rootA = find(a);
55+ int rootB = find(b);
56+ if (rootA == rootB) {return false ;}
57+ if (rootA < rootB) {
58+ parents[rootB] = rootA;
59+ } else {
60+ parents[rootA] = rootB;
61+ }
62+ return true ;
63+ }
64+ }
65+ ```
You can’t perform that action at this time.
0 commit comments