๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 2250๋ฒˆ - ํŠธ๋ฆฌ์˜ ๋†’์ด์™€ ๋„ˆ๋น„

by ์•ˆ์ฃผํ˜• 2022. 8. 14.

๋ฌธ์ œ

 

2250๋ฒˆ: ํŠธ๋ฆฌ์˜ ๋†’์ด์™€ ๋„ˆ๋น„

์ฒซ์งธ ์ค„์— ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜ N(1 ≤ N ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ์ค„๋งˆ๋‹ค ๋…ธ๋“œ ๋ฒˆํ˜ธ์™€ ํ•ด๋‹น ๋…ธ๋“œ์˜ ์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ์™€ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<pair<int,int>>graph[10001];
unordered_map<int,int> cnt;
vector<int> height_arr[10001];

int N, root;
int col[10001];
int seq = 1;
int height = 1;

void inorder(int node){
    
    for(auto next: graph[node]){
        if(next.first != -1){
            height++;
            inorder(next.first);
            height--;
        }
        height_arr[height].push_back(node);
        col[node] = seq++;
        
        if(next.second !=-1){
            height++;
            inorder(next.second);
            height--;
        }
    }
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    cin>>N;
    for(int i=0; i<N; i++){
        int node, first, second;
        cin>>node>>first>>second;
        graph[node].push_back({first,second});
        cnt[node]++;
        cnt[first]++;
        cnt[second]++;
    }
    
    for(auto it = cnt.begin(); it!=cnt.end(); it++){
        if(it->second == 1){
            root = it->first;
            break;
        }
    }
    inorder(root);
    
    int ans_height = 0, ans_width = 0;
    
    for(int i=0; i<=N; i++){
        if(height_arr[i].empty()) continue;
        int width = col[height_arr[i].back()] - col[height_arr[i].front()] + 1;
        int height = i;
        if(width>ans_width){
            ans_width = width;
            ans_height = height;
        }
    }
    cout<<ans_height << ' '<<ans_width;
}

 

ํ’€์ด

 

์ด์ง„ํŠธ๋ฆฌ ํƒ์ƒ‰ ์šดํ–‰๋ฒ•

์ด์ง„ํŠธ๋ฆฌ(Binary Tree) ๋ถ€๋ชจ์™€ ์ž์‹์œผ๋กœ ๋‚˜๋‰˜์–ด ์žˆ๋Š” ํŠธ๋ฆฌ ๊ทธ๋ž˜ํ”„ ๋…ธ๋“œ์˜ ์ตœ๋Œ€ ์ฐจ์ˆ˜๊ฐ€ 2์ด๋ฉฐ, ๊ฐ๊ฐ ์™ผ์ชฝ ์ž์‹(left child), ์™€ ์˜ค๋ฅธ์ชฝ ์ž์‹(right child)์œผ๋กœ ๋‚˜๋‰ฉ๋‹ˆ๋‹ค. ์ด์ง„ํŠธ๋ฆฌ์˜ ์ˆœํšŒ ์ด์ง„ํŠธ๋ฆฌ์˜ ์ˆœํšŒ์—

dkswnkk.tistory.com

๋ฌธ์ œ ์„ค๋ช…์˜ ์ด๋ฏธ์ง€๋ฅผ ์ž˜ ๋ณด๋ฉด ์„ธ๋กœ์—ด์€ ๊นŠ์ด, ๊ฐ€๋กœ ์—ด์€ ์ค‘์œ„ ์ˆœํšŒ(inorder)์˜ ์ˆœ์„œ์ธ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • ๋ฃจํŠธ ๋…ธ๋“œ์˜ ๊ฒฝ์šฐ๋Š” ๋‹จ ํ•œ ๋ฒˆ๋งŒ ์ž…๋ ฅ๊ฐ’์œผ๋กœ ๋“ค์–ด์˜จ ๋…ธ๋“œ๊ฐ€ ๋ฃจํŠธ ๋…ธ๋“œ์ž…๋‹ˆ๋‹ค.
  • ๊ทธ ํ›„ ๊ฐ ์ค‘์œ„ ์ˆœํšŒ ๋ฐฉ์‹์œผ๋กœ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•˜์—ฌ ๊ฐ ๋…ธ๋“œ๋งˆ๋‹ค ๊ฐ€๋กœ ์—ด์˜ ์œ„์น˜(๋„ˆ๋น„)์™€ ์„ธ๋กœ์—ด์˜ ์œ„์น˜(๊นŠ์ด)๋ฅผ ์ €์žฅํ•ด์ค๋‹ˆ๋‹ค.
  • ๊ทธ ํ›„, ๋†’์ด๋งŒํผ ๋ฃจํ”„๋ฅผ ๋Œ์•„ ๊ฐ€์žฅ ๊ธด ๋„ˆ๋น„๋ฅผ ์ฐพ์•„์„œ ์ถœ๋ ฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๋Œ“๊ธ€