优化O(n ^ 2)到O(n)(未排序的字符串)

时间:2012-11-25 17:18:38

标签: c arrays sorting optimization

我在这里遇到了优化问题。我想让这个代码在O(n)中运行,我现在试了几个小时。

字节数组c包含一个字符串,e包含相同的字符串,但已排序。内部数组nc和ne包含字符串中的索引,例如

c:
s l e e p i n g
nc:
0 0 0 1 0 0 0 0 
e:
e e g i l n p s
ne:
0 1 0 0 0 0 0 0

现在的问题是get_next_index是线性的 - 有没有办法解决这个问题?

void decode_block(int p) {
    BYTE xj = c[p];
    int nxj = nc[p];

    for (int i = 0; i < block_size; i++) {
        result[i] = xj;
        int q = get_next_index(xj, nxj, c, nc);
        xj = e[q];
        nxj = ne[q];
    }

    fwrite(result, sizeof (BYTE), block_size, stdout);
    fflush(stdout);
}

int get_next_index(BYTE xj, int nxj, BYTE* c, int* nc) {
    int i = 0;
    while ( ( xj != c[i] ) || ( nxj != nc[i] ) ) {
      i++;
    }
    return i;
}

这是Burrows-Wheeler实施

的一部分

开头
xj = c[p]
nxj = nc[p]

接下来我要block_size(=长度c =长度nc =长度e =长度ne)次

  • 将结果xj存储在结果

  • 找到c [i] == xj

  • 的数字索引
  • xj现在是e [i]

ne和nc仅用于确保e和c中的每个字符都是唯一的(e_0!= e_1)。

3 个答案:

答案 0 :(得分:1)

由于你的宇宙(即一个角色)很小,我认为你可以通过线性时间逃脱。你需要一个链表和 任何序列容器一个查找表。

首先,浏览已排序的字符串并填充查找表,以便查找给定字符的第一个列表元素。例如,您的查找表可能看起来像std::array<std::list<size_t>,(1<<sizeof(char))> lookup。如果您不想要list,您还可以使用std::deque甚至是std::pair<std::vector,size_t>,而第二项代表向量的第一个有效条目的索引(这样您就可以稍后不需要弹出元素,只需增加索引。)

因此,对于已排序字符串中的每个元素c,您可以将其附加到lookup[c]中的容器中。

现在,当您遍历未排序的数组时,对于每个元素,您可以在查找表中查找相应的索引。完成后,在查找表中弹出front元素。

总而言之,这是线性时间和空间。


澄清;初始化查找表时:

// Instead of a list, a deque will likely perform better,
// but you have to test this yourself in your particular case.
std::array<std::list<size_t>,(1<<sizeof(char))> lookup;
for (size_t i = 0; i < sortedLength; i++) {
  lookup[sorted[i]].push_back(i);
}

未排序的数组中找到索引i的“第一个索引”时:

size_t const j = lookup[unsorted[i]].front();
lookup[unsorted[i]].pop_front();
return j;

答案 1 :(得分:1)

扫描xjnxj一次,然后构建一个查找表。这是两个O(n)操作。

最明智的方法是拥有一个二叉树,按xjnxj的值排序。该节点将包含您寻求的索引。这会将您的查找减少到O(lg n)。

答案 2 :(得分:1)

这是我对Burrowes-Wheeler变换的完整实现:​​

u8* bwtCompareBuf;
u32 bwtCompareLen;

s32 bwtCompare( const void* v1, const void* v2 )
{
   u8* c1 = bwtCompareBuf + ((u32*)v1)[0];
   u8* c2 = bwtCompareBuf + ((u32*)v2)[0];

   for ( u32 i = 0; i < bwtCompareLen; i++ )
   {
      if ( c1[i] < c2[i] ) return -1;
      if ( c1[i] > c2[i] ) return +1;
   }
   return 0;
}

void bwtEncode( u8* inputBuffer, u32 len, u32& first )
{
   s8* tmpBuf = alloca( len * 2 );

   u32* indices = new  u32[len];

   for ( u32 i = 0; i < len; i++ ) indices[i] = i;

   bwtCompareBuf = tmpBuf;
   bwtCompareLen = len;
   qsort( indices.data(), len, sizeof( u32 ), bwtCompare );

   u8* tbuf = (u8*)tmpBuf + ( len - 1 );
   for ( u32 i = 0; i < len; i++ )
   {
      u32 idx = indices[i];
      if ( idx == 0 ) idx = len;
      inputBuffer[i] = tbuf[idx];
      if ( indices[i] == 1 ) first = i;
   }

   delete[] indices;
}

void bwtDecode( u8* inputBuffer, u32 len, u32 first )
{
   // To determine a character's position in the output string given
   // its position in the input string, we can use the knowledge about
   // the fact that the output string is sorted.  Each character 'c' will
   // show up in the output stream in in position i, where i is the sum
   // total of all characters in the input buffer that precede c in the
   // alphabet, plus the count of all occurences of 'c' previously in the
   // input stream.

   // compute the frequency of each character in the input buffer
   u32 freq[256] = { 0 };
   u32 count[256] = { 0 };
   for ( u32 i = 0; i < len; i++ )
      freq[inputBuffer[i]]++;

   // freq now holds a running total of all the characters less than i
   // in the input stream
   u32 sum = 0;
   for ( u32 i = 0; i < 256; i++ )
   {
      u32 tmp = sum;
      sum += freq[i];
      freq[i] = tmp;
   }

   // Now that the freq[] array is filled in, I have half the
   // information needed to position each 'c' in the input buffer.  The
   // next piece of information is simply the number of characters 'c'
   // that appear before this 'c' in the input stream.  I keep track of
   // that information in the count[] array as I go.  By adding those
   // two numbers together, I get the destination of each character in
   // the input buffer, and I just write it directly to the destination.
   u32* trans = new u32[len];
   for ( u32 i = 0; i < len; i++ )
   {
      u32 ch = inputBuffer[i];
      trans[count[ch] + freq[ch]] = i;
      count[ch]++;
   }

   u32 idx = first;
   s8* tbuf = alloca( len );
   memcpy( tbuf, inputBuffer, len );
   u8* srcBuf = (u8*)tbuf;
   for ( u32 i = 0; i < len; i++ )
   {
      inputBuffer[i] = srcBuf[idx];
      idx = trans[idx];
   }

   delete[] trans;
} 

O(n)中的解码。