Notice
Recent Posts
Recent Comments
Today
Total
01-25 17:32
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[๋ฐฑ์ค€ 11725] ํŠธ๋ฆฌ์˜ ๋ถ€๋ชจ ์ฐพ๊ธฐ (JAVA) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด

[๋ฐฑ์ค€ 11725] ํŠธ๋ฆฌ์˜ ๋ถ€๋ชจ ์ฐพ๊ธฐ (JAVA)

WonderJay 2023. 1. 22. 11:52
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://www.acmicpc.net/problem/11725

 

11725๋ฒˆ: ํŠธ๋ฆฌ์˜ ๋ถ€๋ชจ ์ฐพ๊ธฐ

๋ฃจํŠธ ์—†๋Š” ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋ฅผ 1์ด๋ผ๊ณ  ์ •ํ–ˆ์„ ๋•Œ, ๊ฐ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net

 

๋”๋ณด๊ธฐ

๋ฌธ์ œ

๋ฃจํŠธ ์—†๋Š” ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋ฅผ 1์ด๋ผ๊ณ  ์ •ํ–ˆ์„ ๋•Œ, ๊ฐ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ N (2 ≤ N ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N-1๊ฐœ์˜ ์ค„์— ํŠธ๋ฆฌ ์ƒ์—์„œ ์—ฐ๊ฒฐ๋œ ๋‘ ์ •์ ์ด ์ฃผ์–ด์ง„๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„๋ถ€ํ„ฐ N-1๊ฐœ์˜ ์ค„์— ๊ฐ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ ๋…ธ๋“œ ๋ฒˆํ˜ธ๋ฅผ 2๋ฒˆ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

์˜ˆ์ œ ์ž…๋ ฅ 1 

7
1 6
6 3
3 5
4 1
2 4
4 7

์˜ˆ์ œ ์ถœ๋ ฅ 1 

4
6
1
3
1
4

์˜ˆ์ œ ์ž…๋ ฅ 2 

12
1 2
1 3
2 4
3 5
3 6
4 7
4 8
5 9
5 10
6 11
6 12

์˜ˆ์ œ ์ถœ๋ ฅ 2 

1
1
2
3
3
4
4
5
5
6
6

์ฃผ์–ด์ง„ ๋ฐ์ดํ„ฐ๋ฅผ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ์— ์–‘๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ ํ˜•ํƒœ๋กœ ์ €์žฅํ•œ ๋‹ค์Œ,

 

๊ฐ ๋…ธ๋“œ์— ๋Œ€ํ•˜์—ฌ DFS ๋ฅผ ๋Œ๋ฉด์„œ,

 

๋ถ€๋ชจ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉด ๋œ๋‹ค.

 

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    static ArrayList<Integer>[] graph;
    static boolean visited[];
    static int parent[];

    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("src/input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer stk;
        int n = Integer.parseInt(br.readLine()); // ์ „์ฒด ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
        graph = new ArrayList[n + 1];
        visited = new boolean[n + 1];
        parent = new int[n + 1];

        for (int i = 0; i <= n; i++)
            graph[i] = new ArrayList<>();

        for (int i = 0; i < n-1; i++) {
            stk = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(stk.nextToken());
            int b = Integer.parseInt(stk.nextToken());
            graph[a].add(b);
            graph[b].add(a);
        }
        for(int i = 1; i<=n; i++){
            dfs(i);
        }
        for(int i = 2 ; i <= n; i++){
            System.out.println(parent[i]);
        }
    }
    static void dfs(int v){
        visited[v] = true;
        for(int cur : graph[v]){
            if(!visited[cur]){
                // ๋ฐฉ๋ฌธ ์•ˆํ–ˆ๋‹ค๋ฉด
                parent[cur] = v;
                dfs(cur);
            }
        }
    }
}

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments