zoukankan      html  css  js  c++  java
  • 寻找hash值——把int array看成是一个整数

    QUESTION:

    Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection, and returns true if a box with the same dominoes was already in the collection and false otherwise. A box of dominoes is encoded as a list of 10 integers from 0 to 9, where a pair of numbers represent a domino. For example: 0,2,9,1,3,3,7,4,5,6 represents a box containing dominoes: (0,2); (9,1); (3,3); (7,4); (5,6). 
    SOLUTION:
    typedef pair< int,int > Domino;
    
    class DominoChecker {
       unordered_set< long long > hash;
       vector< vector< Domino > > boxes;
    
      public:
        bool addBox(const vector< int >& box) {
            vector< Domino > v;
            for (int i = 0; i < 5; i++) {
                Domino d(box[2*i], box[2*i+1]);
                if (d.first > d.second)
                    swap(d.first, d.second); // order does not matter
                v.push_back(d);
            }
            sort(v.begin(), v.end());  // order does not matter here as well.
            long long hash_value = 0;
            for (int i = 0 ; i < 5; i++)
                 hash_value = hash_value * 100 + v[i].first*10 + v[i].second; //把int  array看成是一个整数
            if (hash.find(hash_value) != hash.end())
                return false;
            hash.insert(hash_value);
            boxes.push_back(v); // i suppose we want to store them
            return true;
        }
    };
  • 相关阅读:
    平时十二测
    无题十四
    暑假第十测
    无题十三
    noip错题集
    无题十二
    BZOJ整理
    志愿者招募
    修车
    任务安排
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4830399.html
Copyright © 2011-2022 走看看