nyist 130 相同的雪花(HashMap)

相同的雪花(nyist 130

思路:

每个雪花的六个叶子组成元素可能不同,如果不同,先分类,用HashMap存放,以雪花六个叶子的排序序列ArrayList为键,将六个元素都相同的雪花划分到同一类,即放进同一个集合Vector<ArrayList>中。
在同一类中,当雪花的数量超过 6 ! / 2 360 的时候,一定会出现相同的雪花,因为6个种类的全排列已经全部出现,所以超过 360 的时候一定会出现重复的序列。此时规模很小,Vector的长度不超过 360 ,可以暴力枚举了


本题使用的主要数据结构是HashMap<ArrayList, Vector<ArrayList>>map,接下来请看代码~

JAVA版的AC代码

package nyist.part4dataStructure;

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

/**
 * Created by jal on 2018/5/9 0009.
 */
public class NYIST130HashMap {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        while (T-->0){
            int n = scanner.nextInt();
            HashMap<ArrayList, Vector<ArrayList>>map = new HashMap<ArrayList, Vector<ArrayList>>();
            for(int i = 0; i < n; i++){
                ArrayList temp = new ArrayList();
                for (int j = 0; j < 6; j++){
                    temp.add(scanner.nextInt());
                }
                ArrayList temp2 = (ArrayList) temp.clone();
                Collections.sort(temp2);
                if (!map.containsKey(temp2)){
                    Vector v = new Vector<ArrayList>();
                    v.add(temp);
                    map.put(temp2,v);
                }
                else {
                    Vector v = map.get(temp2);
                    v.add(temp);
                    map.put(temp2, v);
                }
            }
            boolean result = false;
            for (ArrayList listSort : map.keySet()){
                if (map.get(listSort).size() > 360){
                    result = true;
                    break;
                }
                else {
                    Vector v = map.get(listSort);
                    for (int i = 0; i < v.size(); i++){
                        for(int j = i+1; j < v.size(); j++){
                            result = check((ArrayList)v.get(i),(ArrayList)v.get(j));
                            if (result)break;
                        }
                        if (result)break;
                    }
                }
            }
            if (result){
                System.out.print("Twin snowflakes found.\n");
            }
            else {
                System.out.print("No two snowflakes are alike.\n");
            }
        }
    }
    private static boolean check(ArrayList list, ArrayList list1) {
        list1.addAll(list1);
        int index = Collections.indexOfSubList(list1,list);
        if (index != -1)return true;
        Collections.reverse(list1);
        index = Collections.indexOfSubList(list1,list);
        if (index != -1)return true;
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/jal517486222/article/details/80257128
130