11725번: 트리의 부모 찾기

루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.

www.acmicpc.net

 

 

<내 코드>

 

import sys
sys.setrecursionlimit(100000) #런타임 에러 방지

n = int(input())
tree = [[] for _ in range(n+1)]

# 양방향으로 노드를 연결하고
for _ in range(n-1):  # 노드의 수 - 1 (간선)
    a, b = map(int, input().split())
    tree[a].append(b)
    tree[b].append(a)

# 각 노드의 부모 노드 값 저장용
parents = [0 for _ in range(n+1)]
parents[1] = 1


def dfs(curr, tree, parents):
    # print(parents)
    for node in tree[curr]:
        if parents[node] == 0:
            parents[node] = curr  # 해당 자식 노드에 부모노드(curr) 값 넣음
            dfs(node, tree, parents)  # 자식 노드가 서브 트리 루트로서 탐색


dfs(1, tree, parents)

print(*parents[2:])

 

반응형

 

 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자

www.acmicpc.net

<내 코드>

def preorder(node):
    if node == '.':
        return
    print(node, end="")
    preorder(tree[node][0])  # tree[key][value], 왼쪽 자식 노드
    preorder(tree[node][1])  # 오른쪽 자식 노드


def inorder(node):
    if node == '.':
        return
    inorder(tree[node][0])  # 왼쪽 자식 노드
    print(node, end="")
    inorder(tree[node][1])  # 오른쪽 자식 노드


def postorder(node):
    if node == '.':
        return
    postorder(tree[node][0])  # 왼쪽 자식 노드
    postorder(tree[node][1])  # 오른쪽 자식 노드
    print(node, end="")


n = int(input())
tree = {}

# tree 생성
for _ in range(n):
    root, left, right = input().split()
    tree[root] = (left, right)

#print(tree)
preorder('A')
print()
inorder('A')
print()
postorder('A')

 

딕셔너리를 이용해 트리를 만들어준다. 그다음 각 순회 방식에 맞게 재귀를 이용해 함수를 작성해준다.

 

# tree
{
  'A': ('B', 'C'), 
  'B': ('D', '.'), 
  'C': ('E', 'F'), 
  'E': ('.', '.'), 
  'F': ('.', 'G'), 
  'D': ('.', '.'), 
  'G': ('.', '.')
}
반응형

 

 

2798번: 블랙잭

첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는다. 합이 M을 넘지 않는 카드 3장을 찾을 수 있�

www.acmicpc.net

 

 

<내 코드>

 

N, M = map(int, input().split())
nums = list(map(int, input().split()))
sum = 0
for i in range(N-2):
    for j in range(i+1, N-1):
        for k in range(j+1, N):
            if ((nums[i] + nums[j] + nums[k]) > M):
                continue
            else:
                sum = max(sum, nums[i] + nums[j] + nums[k])
print(sum)

 

from itertools import combinations

N, M = map(int, input().split())
nums = list(map(int, input().split()))
result = 0

for cards in combinations(nums, 3):
    sum_num = sum(cards)

    if sum_num <= M and sum_num > result:
        result = sum_num

print(result)

 

파이썬에서 제공하는 순열 조합을 구하는 모듈인 combinations을 이용해 모든 경우를 구한다.

combinations(리스트, 몇 개씩 조합할지) 정해주면 된다.

반응형

1. type이 sk인, name으로 구성된 배열만 출력

 

data =
  [{
    "id": 1,
    "name": "Yong",
    "phone": "010-0000-0000",
    "type": "sk",
    "childnode": [{
      "id": 11,
      "name": "echo",
      "phone": "010-0000-1111",
      "type": "kt",
      "childnode": [{
        "id": 115,
        "name": "hary",
        "phone": "211-1111-0000",
        "type": "sk",
        "childnode": [{
          "id": 1159,
          "name": "pobi",
          "phone": "010-444-000",
          "type": "kt",
          "childnode": [{
            "id": 11592,
            "name": "cherry",
            "phone": "111-222-0000",
            "type": "lg",
            "childnode": []
          },
          {
            "id": 11595,
            "name": "solvin",
            "phone": "010-000-3333",
            "type": "sk",
            "childnode": []
          }
          ]
        }]
      },
      {
        "id": 116,
        "name": "kim",
        "phone": "444-111-0200",
        "type": "kt",
        "childnode": [{
          "id": 1168,
          "name": "hani",
          "phone": "010-222-0000",
          "type": "sk",
          "childnode": [{
            "id": 11689,
            "name": "ho",
            "phone": "010-000-0000",
            "type": "kt",
            "childnode": [{
              "id": 116890,
              "name": "wonsuk",
              "phone": "010-000-0000",
              "type": "kt",
              "childnode": []
            },
            {
              "id": 1168901,
              "name": "chulsu",
              "phone": "010-0000-0000",
              "type": "sk",
              "childnode": []
            }
            ]
          }]
        }]
      },
      {
        "id": 117,
        "name": "hong",
        "phone": "010-0000-0000",
        "type": "lg",
        "childnode": []
      }
      ]
    }]
  }]
let arr = [];
function parsing(data) {
  data.forEach(k => {
    if (k.type === 'sk') {
      arr.push(k.name);
    }
    if (k.childnode.length > 0) {
      parsing(k.childnode);
    }
  });
}

parsing(data);
console.log(arr);
// 출력
[ 'Yong', 'hary', 'solvin', 'hani', 'chulsu' ]

 

 

2. 숫자 타입으로만 구성된 요소를 뽑아 배열로 만들기

 

const data = {
  "debug": "on",
  "window": {
    "title": "Sample Konfabulator Widget",
    "name": "main_window",
    "width": 500,
    "height": 500
  },
  "image": {
    "src": "Images/Sun.png",
    "name": "sun1",
    "hOffset": 250,
    "vOffset": 250,
    "alignment": "center"
  },
  "text": {
    "data": "Click Here",
    "size": 36,
    "style": "bold",
    "name": "text1",
    "hOffset": 250,
    "vOffset": 100,
    "alignment": "center",
    "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
  }
};

let arr = [];
function parsing(data) {
  for (item in data) {
    if (typeof (data[item]) === 'object') {
      parsing(data[item]);
    }
    else if (typeof (data[item]) === 'number') {
      arr.push(item);
    }

  };
}
parsing(data);
console.log(arr)
// 출력 
["width", "height", "hOffset", "vOffset", "size", "hOffset", "vOffset"]
반응형

+ Recent posts