从序列中找四个四字子串形成十进制数使之乘积最大(就是求四个最大的?),我目前只想到如下办法。这个题并不是关于复杂的算法,其本意是要利用并行处理,但目前尚未考虑到(除了其中比较求最小值部分有希望用SIMD)。
#include <stdio.h>
int g_TestString[] = {
8,9,9,0,1,2,8,6,9,8,0,1,7,9,2,3,1,5,2,3,1,7,2,8,9,7,6,8,9,0,2,5,1,7,3,4,8,9,0,7,3,1,2
};
int main (void)
{
int i, j;
int n = sizeof(g_TestString) / sizeof(int);
int picked[4] = {0,0,0,0};
int pickedFrom[4] = {-1,-1,-1,-1};
int least = 99999; /* big enough */
int leastPos = 0;
/* first fueling */
int cur = 0;
for (i = 0; i < 4; i++)
{
cur *= 10;
cur += g_TestString[i];
}
for (i = 0; i < 4; i++)
{
picked[i] = cur;
pickedFrom[i] = i;
if (cur < least)
{
least = cur;
leastPos = i;
}
cur -= g_TestString[i] * 1000;
cur *= 10;
cur += g_TestString[i + 4];
}
for (i = 4; i < n - 4; i++)
{
if (least < cur)
{
int tempLeast, tempLeastPos;
picked[leastPos] = cur;
pickedFrom[leastPos] = i;
/* refresh */
if (picked[0] < picked[1])
{
tempLeast = picked[0];
tempLeastPos = 0;
}
else
{
tempLeast = picked[1];
tempLeastPos = 1;
}
if (picked[2] < picked[3])
{
least = picked[2];
leastPos = 2;
}
else
{
least = picked[3];
leastPos = 3;
}
if (tempLeast < least)
{
least = tempLeast;
leastPos = tempLeastPos;
}
}
cur -= g_TestString[i] * 1000;
cur *= 10;
cur += g_TestString[i + 4];
}
for (i = 0; i < 4; i++)
{
printf("%d picked from %d/n", picked[i], pickedFrom[i]);
}
return 0;
}
输出结果:
9231 picked from 13
9901 picked from 1
9768 picked from 24
9801 picked from 8