[백준] 11725번 : 트리의 부모 찾기 - C#

강재원·2022년 12월 1일
0

[코딩테스트] C#

목록 보기
192/200



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

using System;
using System.Collections;
using System.Text;

class Program
{
    static ArrayList[] arr;
    static int[] num;
    static bool[] check;
    static int n,bf;
    
    static void dfs(int a){
        check[a]=true;
        num[a]=bf;
        
        foreach(int i in arr[a]){
            if(check[i]==false){
                bf=a;
                dfs(i);
            }
        }
    }
    
    static void Main() {
        StringBuilder sb = new StringBuilder();
        string s=Console.ReadLine();
        n=int.Parse(s);
        arr=new ArrayList[n+1];
        for(int i=0;i<=n;i++) arr[i]=new ArrayList();
        num=new int[n+1];
        check=new bool[n+1];
        
        for(int i=0;i<n-1;i++){
            string[] s1=Console.ReadLine().Split(' ');
            int u=int.Parse(s1[0]);
            int v=int.Parse(s1[1]);
            arr[u].Add(v);
            arr[v].Add(u);
        }
        bf=1;
        dfs(1);
        for(int i=2;i<=n;i++) sb.AppendLine(num[i].ToString());
        Console.Write(sb.ToString());
    }
}
profile
개념정리 & 문법 정리 & 알고리즘 공부

0개의 댓글