알고리즘

[BOJ] 14713 - 앵무새 (Python, JavaScript)

흙금 2023. 5. 22. 12:26

 

 

아이디어

 

맵을 이용해 모든 단어들이 순서에 맞게 적혀 있는지 확인한다.

 

 

풀이 #1 (Python)

 

import sys

input = sys.stdin.readline

def solution():
    N = int(input())
    sentences = [input().split() for _ in range(N)]
    idx_dict = dict()
    for i in range(N):
        idx_dict[sentences[i].pop()] = i
    L = input().split()
    while L:
        word = L.pop()
        idx = idx_dict.get(word, -1)
        idx_dict[word] = -1
        if idx >= 0:
            if sentences[idx]:
                idx_dict[sentences[idx].pop()] = idx
        else:
            print('Impossible')
            return
    print('Possible')

solution()

 

 

 

풀이 #2 (JavaScript)

 

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');

function solution() {
    const N = Number(input[0]);
    let sentences = [];
    for (let i=1; i<=N; i++) {
        sentences.push(input[i].split(' '));
    }
    let idxMap = new Map();
    for (let i=0; i<N; i++) {
        idxMap.set(sentences[i].pop(), i+1);
    }
    let L = input[N+1].split(' ');
    while (L.length) {
        const word = L.pop();
        const idx = idxMap.get(word);
        idxMap.set(word, 0);
        if (idx) {
            if (sentences[idx-1]) idxMap.set(sentences[idx-1].pop(), idx);
        }
        else {
            console.log('Impossible');
            return
        }
    }
    console.log('Possible');
}

solution();