14725번: 개미굴

첫 번째 줄은 로봇 개미가 각 층을 따라 내려오면서 알게 된 먹이의 정보 개수 N개가 주어진다.  (1 ≤ N ≤ 1000) 두 번째 줄부터 N+1 번째 줄까지, 각 줄의 시작은 로봇 개미 한마리가 보내준 먹이

www.acmicpc.net

 

 

 

 


 

  • 풀이

 

개미굴의 각 층을 표현하고 같은 층의 경우 사전순으로 먼저 출력되야 합니다.

 

TreeMap의 장점 중 하나는 자동으로 key값에 의해 자동 정렬 된다는 것입니다. (우선순위 큐와 비슷한 느낌)

 

저 같은 경우 Node라는 class를 만들어 현재 string과 자식 Treemap을 생성해 주었다.

 

 

맨 처음 연결시킬 string 입력이 올 시 now라는 Node를 만들어 준 뒤 root의 위치를 할당합니다. 그 후 입력된 String이 자식 Treemap의 키값 중 해당 String으로 된 TreeMap이 없다면 새롭게 자식 TreeMap을 만들어 연결 시켜줍니다. 그 후, now를 자식 node를 가리키게 합니다. (해당 동작은 자식 노드를 게속 연결시켜주기 위함.)

 

연결이 모두 다 되었다면, root에 연결된 자식 TreeMap을 하나씩 꺼내서 자식을 타고가면서 출력해주면 됩니다.

저는 재귀 형식으로 구현했습니다.

 

 

 


 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class Main {
	static StringBuilder sb;
	
	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(sb);
	}
    
	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

        int n = in.nextInt();
        Trie trie = new Trie("");
        Trie node;
        sb = new StringBuilder();
        
        while(n-- > 0) {
        	String[] temp = in.nextLine().split(" ");
            int k = Integer.parseInt(temp[0]);
            node = trie;
            
            for(int j = 0 ; j < k ; j++) {
                String name = temp[j+1];
                
                if(!node.list.containsKey(name)) 
                    node.list.put(name, new Trie(name));
                
                node = node.list.get(name);
            }
        }
        
        print(trie, -1);
    }
    
    public static void print(Trie trie, int depth) {
        if(depth != -1) {
            for(int i = 0; i < depth; i++) {
                sb.append("--");
            }
            sb.append(trie.name).append("\n");
        }
        
        for(Trie tree : trie.list.values()) {
            print(tree, depth+1);
        }
    }
}

class Trie{
    TreeMap<String, Trie> list;
    String name;
    
    Trie(String name) {
        list = new TreeMap<>();
        this.name = name;
    }
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

+ Recent posts