You are given a list dishes, where each element consists of a list of strings beginning with the name of the dish, followed by all the ingredients used in preparing it. You want to group the dishes by ingredients, so that for each ingredient you'll be able to find all the dishes that contain it (if there are at least 2 such dishes).

Return an array where each element is a list beginning with the ingredient name, followed by the names of all the dishes that contain this ingredient. The dishes inside each list should be sorted lexicographically, and the result array should be sorted lexicographically by the names of the ingredients.

Example

Input/Output

풀이

String[][] solution(String[][] dishes) {
    // 사전순 정렬을 위한 자료구조
    TreeMap <String, TreeSet <String>> map = new TreeMap<>();
    
    for (String [] arr : dishes) {
        // 요리 이름은 0 인덱스 위치
        String dish = arr[0];
        
        // 재료 : [요리1, 요리2, ...]
        for (int i = 1; i < arr.length; i ++) {
            String ingre = arr[i];
            
            if (!map.containsKey(ingre)) {
                TreeSet <String> set = new TreeSet <String> ();
                set.add(dish);
                map.put(ingre, set);
            } else {
                TreeSet <String> set = map.get(ingre);
                set.add(dish);
                map.put(ingre, set);
            }
        }
    }
    
    // 가변형 자료구조
    LinkedList <String []> buffer = new LinkedList<>();
    
    for (String s : map.keySet()) {
        // 재료에 두 가지 이상 요리가 존재
        if (map.get(s).size() > 1) {
            String [] buff = new String [map.get(s).size() + 1];
            int idx = 1;
            buff[0] = s;
            
            for (String _s : map.get(s)) {
                buff[idx ++] = _s;
            }
            
            buffer.add(buff);
        }
    }
    
    String [][] result = new String [buffer.size()][];
    
    for (int i = 0; i < result.length; i ++) {
        result[i] = buffer.get(i);
    }
    
    return result;
}