# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
745696 | 2023-05-21T02:37:55 Z | rahulverma | Network (BOI15_net) | Java 11 | 0 ms | 0 KB |
import java.io.*; import java.util.*; public class network { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i = 0; i < n; i++) graph.add(new ArrayList<Integer>()); for(int i = 1; i < n; i++) { int v1 = s.nextInt() - 1; int v2 = s.nextInt() - 1; graph.get(v1).add(v2); graph.get(v2).add(v1); } int root = 0; for(int i = 0; i < n; i++) { if(graph.get(i).size() != 1) { root = i; } } int[] dist = new int[n]; Queue<Integer> q = new LinkedList<Integer>(); Arrays.fill(dist, -1); q.add(root); dist[root] = 0; ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(root); while(!q.isEmpty()) { int node = q.poll(); for(int node2: graph.get(node)) { if(dist[node2] == -1) { dist[node2] = dist[node] + 1; q.add(node2); if(graph.get(node2).size() == 1) { ans.add(node2 + 1); } } } } /*for(int i = 0; i < n; i++) { System.out.println(dist[i]); }*/ System.out.println(ans.size() / 2); for(int i = 0; i < ans.size(); i += 2) { System.out.println(ans.get(i) + " " + ans.get(i + 1)); } } }