我有这个问题: 有N行数的K行(32位)。我必须选择具有最大数字乘积的行。
主要问题是N可以达到20。 我试图用对数来做这个:
ld sum = 0, max = 0;
int index = 0;
for(int i = 0; i < k; i ++) { // K lines
sum = 0, c = 0;
for(int j = 0; j < n; j ++) { // N numbers
cin >> t;
if(t < 0)
c++; // If the number is less than 0 i memorize it
if(t == 1 || t == -1) { // if numbers = 1 OR -1
sum += 0.00000001; // Because log(1) = 0
if(t == -1)
c ++;
}
else if(t == 0) { // if some number is equal to zero then the sum is = 0
sum = 0;
break;
}
else {
sum += log10(fabs(t));
}
}
if(c % 2 == 1) // if c is odd than multiply by -1
sum *= -1;
if(sum >= max) {
max = sum;
index = i;
}
if((sum - max) < eps) { // if sum is equal to max i'm also have to choose it
max = sum;
index = i;
}
}
cout << index + 1 << endl;
该程序适用于50%的测试用例。有没有办法优化我的代码?
答案 0 :(得分:1)
在t == -1的情况下,你将c增加两次。
答案 1 :(得分:0)
我认为这一行肯定是错误的:
if(c % 2 == 1) // if c is odd than multiply by -1
sum *= -1;
如果您的产品在[0,1]范围内,则其对数将为负数,这将使其为正数。我认为你应该把它分开。
答案 2 :(得分:0)
如果你想避免bignum libs你可以利用它,如果你乘以b1
和b2
位数,那么结果是b1+b2
位长
所以只需将一行中所有被乘数的位数相加
记住某些数组中的结果
int bits(DWORD p) // count how many bits is p DWORD is 32bit unsigned int
{
DWORD m=0x80000000; int b=32;
for (;m;m>>=1,b--)
if (p>=m) break;
return b;
}
index按结果位计数降序排序
现在乘法
另一种乘法方法
bignum multiplication