提交记录 14117


用户 题目 状态 得分 用时 内存 语言 代码长度
onionyst router32. 测测你的路由器 Compile Error 0 0 ns 0 KB C 1.56 KB
提交时间 评测时间
2020-09-13 02:01:15 2020-09-13 02:01:16
#include "router.h"
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  RoutingTableEntry entry;
  uint32_t next[2];
} TrieNode;

TrieNode trie[10000];
uint32_t index = 0;

void update(bool insert, RoutingTableEntry entry) {
  if (insert) {
    int ptr = 0;
    for (uint32_t i = 0; i < entry.len; i++) {
      int b = (entry.addr >> i) & 0x1;
      if (trie[ptr].next[b] == 0) {
        trie[ptr].next[b] = ++index;
        ptr = index;
        trie[ptr].entry.addr = entry.addr & ((1 << (i + 1)) - 1);
      } else {
        ptr = trie[ptr].next[b];
      }
    }
    trie[ptr].entry.len = entry.len;
    trie[ptr].entry.nexthop = entry.nexthop;
  } else {
    int ptr = 0;
    for (uint32_t i = 0; i < entry.len; i++) {
      int b = (entry.addr >> i) & 0x1;
      if (trie[ptr].next[b] == 0) {
        return;
      }
      ptr = trie[ptr].next[b];
    }
    trie[ptr].entry.len = 0;
    trie[ptr].entry.nexthop = 0;
  }
}

bool prefix_query(uint32_t addr, uint32_t *nexthop) {
  int match = (trie[0].entry.len != 0) ? 0 : -1;

  int ptr = 0;
  for (uint32_t i = 0; i < 32; i++) {
    int b = (addr >> i) & 0x1;
    if (trie[ptr].next[b] == 0) {
      break;
    }
    ptr = trie[ptr].next[b];
    if (trie[ptr].entry.len != 0) {
      match = trie[ptr].entry.len;
      *nexthop = trie[ptr].entry.nexthop;
    }
  }

  return match >= 0;
}

void init(int n, int q, const RoutingTableEntry *a) {
  for (int i = 0; i < n; i++) {
    update(true, a[i]);
  }  
}

unsigned query(unsigned addr) {
  uint32_t nexthop;
  if (!prefix_query(addr, &nexthop)) {
    return 0;
  }
  return nexthop;
}

CompilationN/AN/ACompile ErrorScore: N/A


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