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 38 39 40 41 42
| public class boj_11725 { static List<List<Integer>> graphList; static boolean[] isChecked; static int[] parent; public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st; graphList = new ArrayList<>(); isChecked = new boolean[n+1]; parent = new int[n+1]; for(int i=0; i<=n; i++){ graphList.add(new ArrayList<>()); }
for(int i=0; i<n-1; i++){ st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); graphList.get(x).add(y); graphList.get(y).add(x); } findParent(1); for(int i=2; i<parent.length; i++){ System.out.print(parent[i] + " "); }
}
private static void findParent(int x) { isChecked[x] = true; for(int i=0; i<graphList.get(x).size(); i++){ int y = graphList.get(x).get(i); if(!isChecked[y]){ parent[y] = x; findParent(y); } } } }
|