提交记录 29022


用户 题目 状态 得分 用时 内存 语言 代码长度
217965 router32. 测测你的路由器 Wrong Answer 50 4.623 s 42080 KB C++ 1.21 KB
提交时间 评测时间
2026-06-16 18:26:19 2026-06-16 18:26:29
#include "router.h"
#include <unordered_map>
#include <cstdint>

// 使用一个全局的哈希表来存储路由表项
// key: (addr << 8) | len  (因为 len 的范围是 0~32,占用 6 个 bit,左移 8 位足够避免冲突)
// value: nexthop
static std::unordered_map<uint64_t, unsigned> routing_map;

void init(int n, int q, const RoutingTableEntry *a) {
    // 清空并预留空间,减少哈希表动态扩容带来的开销
    routing_map.clear();
    routing_map.reserve(n);
    
    for (int i = 0; i < n; ++i) {
        // 构造哈希表的 key
        // addr 是大端序,直接作为整数参与位运算是安全的,
        // 因为大端序的高位在内存低地址,与 IP 前缀从左到右的顺序一致。
        uint64_t key = (static_cast<uint64_t>(a[i].addr) << 8) | a[i].len;
        routing_map[key] = a[i].nexthop;
    }
}

unsigned query(unsigned addr) {
    // 从最长前缀 (32) 开始向下匹配到默认路由 (0)
    for (int len = 32; len >= 0; --len) {
        // 提取前 len 位的前缀
        // 当 len = 0 时,mask = 0,prefix = 0
        // 当 len = 32 时,mask = 0xFFFFFFFF,prefix = addr
        unsigned mask = (len == 0) ? 0 : (0xFFFFFFFFU << (32 - len));
        unsigned prefix = addr & mask;
        
        // 在哈希表中查找
        uint64_t key = (static_cast<uint64_t>(prefix) << 8) | len;
        auto it = routing_map.find(key);
        if (it != routing_map.end()) {
            return it->second;
        }
    }
    
    // 未找到匹配项,返回 0
    return 0;
}

CompilationN/AN/ACompile OKScore: N/A

Testcase #116.93 us24 KBAcceptedScore: 25

Testcase #299.897 ms41 MB + 96 KBAcceptedScore: 25

Testcase #32.364 s41 MB + 96 KBWrong AnswerScore: 0

Testcase #44.623 s41 MB + 96 KBWrong AnswerScore: 0


Judge Duck Online | 评测鸭在线
Server Time: 2026-06-28 06:19:10 | Loaded in 1 ms | Server Status
个人娱乐项目,仅供学习交流使用 | 捐赠