关于你的大的恒定位数组,大段常量,这里有一个替代方法来设计表格供你考虑(我不知道你确切的需求,所以我不能说它是否会帮助或不)。
考虑类似于radix tree。为了便于说明,让我定义get函数:
#define TYP_CONST
#define TYP_ARRAY
struct node {
unsigned min;
unsigned max;
int typ;
union {
char *bits;
int constant;
} d;
struct node *left;
struct node *right;
}
struct bit_array {
unsigned length;
struct node *root;
}
int get(struct bit_array *b, unsigned ix)
{
struct node *n = b->root;
if (ix >= b->length)
return -1;
while (n) {
if (ix > n->max) {
n = n->right;
continue;
} else if (ix < n->min) {
n = n->left;
continue;
}
if (n->typ == TYP_CONST)
return n->d.constant;
ix -= n->min;
return !!(n->d.bits[ix/8] & (1 << ix%8));
}
return -1;
}
对人类而言,您希望通过树的位进行搜索。每个节点负责一定范围的位,并且通过对范围进行二进制搜索以找到您想要的范围。
找到范围后,有两个选项:常量或数组。如果不变,只需返回常量(为您节省大量内存)。如果是数组,则在位数组中执行数组查找。
你将有O(log n)查找时间,而不是O(1)....虽然它应该仍然非常快。
这里的难点在于设置合适的数据结构很烦人且容易出错。但是你说阵列是恒定的,所以这可能不成问题。
我怀疑这是NP难,因为没有办法建立一个命令来处理这些可能会导致DP样解决方案,但我没有知识来证明它。你可能会得到更好的理论或mathoverflow回答 – dfb 2012-04-23 18:40:13