提交记录 29022
| 提交时间 |
评测时间 |
| 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;
}
| Compilation | N/A | N/A | Compile OK | Score: N/A | 显示更多 |
| Testcase #1 | 16.93 us | 24 KB | Accepted | Score: 25 | 显示更多 |
| Testcase #2 | 99.897 ms | 41 MB + 96 KB | Accepted | Score: 25 | 显示更多 |
| Testcase #3 | 2.364 s | 41 MB + 96 KB | Wrong Answer | Score: 0 | 显示更多 |
| Testcase #4 | 4.623 s | 41 MB + 96 KB | Wrong Answer | Score: 0 | 显示更多 |
Judge Duck Online | 评测鸭在线
Server Time: 2026-06-28 06:19:10 | Loaded in 1 ms | Server Status
个人娱乐项目,仅供学习交流使用 | 捐赠