[백준] 14244번: 트리 만들기

whitehousechef·2023년 11월 2일
0

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

initial

I found this explanation useful: https://blog.everdu.com/137

This question is a second tree question I tried solving (but to no avail). The example in the q gave as binary tree so I tried impl that way but we just need leaf nodes that is all. So for example when we need 3 leaf nodes, we can have a central node and have 3 other child nodes connect to that central node. But when we need 2 leaf nodes, we need 1 long branch of nodes.

So the way to think is that first we have a central node and that already is considered a leaf so we increment leaf variable by 1. Then, so as not to exceed the number of leaf nodes, we keep connecting the rest of the nodes to the original node’s leaf (like print tracked_child_leaf,i). So as we iterate from 1 to n, when m>leaf like given 3 leaves, we can just connect the iter i to original i node like print(0,i) and increment leaf. BUT else, we need to connect the incoming node i to the previous child node like print(tracked_child_leaf,i) so as for the total leaves to not exceed m. We keep updating this tracked_child_leaf to i so that next node can connect to this i node as a child leaf node.

solution

n, m = map(int, input().split())
leaf = 0

# If there are only 2 nodes, consider one of them as a leaf
if m == 2:
    leaf = 1

last_leaf = 0

# Iterate through the nodes from 1 to n-1
for i in range(1, n):
    if m > leaf:
        # If there is a need for more leaf nodes, connect the current node to node i
        print(0, i)
        leaf += 1
    else:
        # If there are enough leaf nodes, connect the current node to the last leaf node
        print(last_leaf, i)
    
    last_leaf = i  # Update the last connected leaf node

complexity

The time complexity of the provided code is O(n) because it uses a loop that iterates from 1 to n-1. The number of iterations in this loop is directly proportional to the value of n, making the time complexity linear with respect to the number of nodes.

The space complexity of the code is O(1) because it uses a constant amount of additional space to store variables like leaf, last_leaf, and the loop index i. The space required does not depend on the size of the input n or m.

0개의 댓글