跳到正文

题解

题解:P11615 【模板】哈希表

zp20120123约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年1月26日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 4 分钟
题目
P11615

版本

  1. v1当前

作为一个蒟蒻, 我不想说什么了,代码有注释,大家可以自行理解(较详细)

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>

// 快读函数相关
char buf[1 << 23], *p1 = buf, *p2 = buf;
#define gc() (p1 == p2 && (p2 = (p1 = buf) + std::fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)

// 快速读取无符号长整型
inline unsigned long long rd() {
    unsigned long long x = 0;
    char ch = gc();
    // 跳过非数字字符
    while (!std::isdigit(ch)) ch = gc();
    // 读取数字字符并转换为数字
    while (std::isdigit(ch)) {
        x = x * 10 + (ch ^ 48);
        ch = gc();
    }
    return x;
}

const int HASH_SIZE = 1e7 + 3;

// 哈希表结构体
struct HashTable {
    unsigned long long key[HASH_SIZE]; // 存储键
    unsigned long long value[HASH_SIZE]; // 存储值
    bool used[HASH_SIZE]; // 标记是否被使用

    // 构造函数,初始化哈希表
    HashTable() {
        std::memset(used, 0, sizeof(used));
    }

    // 哈希函数
    size_t hash(unsigned long long x) {
        return x % HASH_SIZE;
    }

    // 插入键值对
    void insert(unsigned long long k, unsigned long long v) {
        size_t pos = hash(k);
        // 线性探测,处理哈希冲突
        while (used[pos] && key[pos] != k) {
            pos = (pos + 1) % HASH_SIZE;
        }
        key[pos] = k;
        value[pos] = v;
        used[pos] = true;
    }

    // 查询键对应的值
    unsigned long long find(unsigned long long k) {
        size_t pos = hash(k);
        // 线性探测,查找键
        while (used[pos]) {
            if (key[pos] == k) {
                return value[pos];
            }
            pos = (pos + 1) % HASH_SIZE;
        }
        return 0; // 未找到,返回0
    }
};

int main() {
    int n = rd();
    unsigned long long sum = 0;
    HashTable f;

    for (int i = 1; i <= n; i++) {
        unsigned long long x = rd();
        unsigned long long y = rd();
        // 查询当前键对应的值
        unsigned long long ans = f.find(x);
        // 更新键对应的值
        f.insert(x, y);
        // 累加结果
        sum += i * ans;
    }
    std::cout << sum;
    return 0;
}
原文