跳到正文

剪贴板

剪贴板 ixuzx47u

原文
剪贴板信息

剪贴板信息

收录
更新
C++
template <typename Key, typename T, unsigned n, unsigned p>
struct UNORDERED_MAP {
    // Key : key type (signed/unsigned int/long long)
    // T : value type
    // n : the maximum total number of times insert() and operator[] is called
    // p : number of buckets
    unsigned hsh(unsigned long long x) const {
        static const unsigned long long t = std::chrono::steady_clock::now().time_since_epoch().count();
        x += t + 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return (x ^ (x >> 31)) % p;
    }
    struct Q {
        Key x;
        T y;
        unsigned z;
    } e[n + 1];
    unsigned h[p], idx, sz;
    bool empty() const { return !sz; }
    unsigned size() const { return sz; }
    void clear() {
        for (unsigned i = 1; i <= idx; ++i) h[hsh(e[i].x)] = 0, e[i] = e[i - 1];
        idx = sz = 0;
    }
    Q *find(const Key &x) {
        auto z = hsh(x);
        for (auto i = h[z]; i; i = e[i].z)
            if (e[i].x == x)
                return &e[i];
        return 0;
    }
    std::pair<Q *, bool> insert(const Key &x, const T &y) {
        auto z = hsh(x);
        for (auto i = h[z]; i; i = e[i].z)
            if (e[i].x == x)
                return std::make_pair(&e[i], 0);
        ++idx, ++sz, e[idx].x = x, e[idx].y = y, e[idx].z = h[z], h[z] = idx;
        return std::make_pair(&e[idx], 1);
    }
    bool erase(const Key &x) {
        auto z = hsh(x);
        for (auto i = h[z], j = -1; i; j = i, i = e[i].z)
            if (e[i].x == x)
                return (~j ? e[j].z : h[z]) = e[i].z, --sz, 1;
        return 0;
    }
    T &operator[](const Key &x) {
        auto z = hsh(x);
        for (auto i = h[z]; i; i = e[i].z)
            if (e[i].x == x)
                return e[i].y;
        ++idx, ++sz, e[idx].x = x, e[idx].z = h[z], h[z] = idx;
        return e[idx].y;
    }
};
UNORDERED_MAP<ULL, int, 1000000, 19260817> mp;