5052번: 전화번호 목록

첫째 줄에 테스트 케이스의 개수 t가 주어진다. (1 ≤ t ≤ 50) 각 테스트 케이스의 첫째 줄에는 전화번호의 수 n이 주어진다. (1 ≤ n ≤ 10000) 다음 n개의 줄에는 목록에 포함되어 있는 전화번호가

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 생각

 

입력한 모든 숫자 중 한 가지의 숫자가 다른 숫자에 시작으로 포함되어있으면 안되는 문제이다.

 

이때 정수로 오름차순 정렬하면 정말 크고작은 수대로 정렬이 되기때문에 원하는 대로 정렬이 안된다.

여기서 문자열로 받은다음 정렬하면 원하는대로 정렬 될것이다.

그래서 정렬 후 i-1인덱스의 값이 i인덱스의 값에 startsWith를 사용해서 접두어 관계를 가지는지 확인만 해주면 된다.

 

 

 

 

  • 코드

 

 

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;

public class Main {
	static StringBuilder sb;
	static int N, L, answer;

	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 testcase = in.nextInt();
		sb = new StringBuilder();
		int n;
		boolean check;
		
		for(int i=0;i<testcase;i++)
		{
			check = false;
			n = in.nextInt();
			String[] array = new String[n];
            for(int j=0;j<n;j++) {
                array[j]=in.nextLine();
            }
            
            //정렬과 스위치 구현
            Arrays.sort(array, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);                    
                }
            });
            
            for(int j=1;j<n;j++) {
                if(array[j].startsWith(array[j-1])) {
                    check=true;
                    break;
                }
            }
            
            if(check) sb.append("NO").append("\n");
            else sb.append("YES").append("\n");
		}		
	}
	
}

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;
	}
}

 

 

 

  • 트라이 방법?

트라이 방법으로 풀 수 있다고하는데 속도는 빠르지만 메모리를 너무 많이 잡아먹어서 장단점이 있는 것 같다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int TC = Integer.parseInt(br.readLine());

        root:
        for (int tc = 0; tc < TC; tc++) {
            int n = Integer.parseInt(br.readLine());
            HTrie root = new HTrie('r', true);
            boolean check = true;
            for (int i = 0; i < n; i++) {
                char[] input = br.readLine().toCharArray();
                if (check) {
                    if (!root.insert(input)) {
                        check = false;
                    }
                }
            }
            if (check) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }
        }
    }


    static class HTrie {
        char number;
        boolean isRoot;
        boolean isEnd;
        HTrie[] children;

        HTrie(char number, boolean isRoot) {
            this.number = number;
            this.isRoot = isRoot;
            children = new HTrie[10];
        }

        boolean insert(char[] numbers) {
            HTrie t = this;

            for (int i = 0; i < numbers.length; i++) {
                char c = numbers[i];
                int id = c - '0';

                if (t.children[id] == null) {
                    t.children[id] = new HTrie(c, false);
                } else {
                    if (t.children[id].isEnd && i != numbers.length - 1) {
                        return false;
                    }

                    if (i == numbers.length - 1) {
                        return false;
                    }
                }

                t = t.children[id];

                if (i == numbers.length - 1) {
                    t.isEnd = true;
                }
            }

            return true;
        }
    }
}

+ Recent posts