![](/img/trans.png)
[英]Is there any way to reduce time complexity to find this matrix to the power n?
[英]Is there any way to merge two (or multiple) for loops to reduce the overall time complexity?
实际上我已经解决了比较计算结果并返回最小值的问题。 虽然我成功地实现了逻辑并很好地执行了代码,但未能降低时间复杂度。
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;
int checkMinimum(int array[], int index)
{
int result = INT_MAX;
for(int i = 0; i < index; ++i)
for(int j = 0; j < index; ++j)
if(i != j && (min(result, ((array[i] & array[j]) ^ (array[i] | array[j]))) < result))
result = min(result, ((array[i] & array[j]) ^ (array[i] | array[j])));
return result;
}
void getMinimum()
{
int index;
cin >> index;
int array[index];
for(int i = 0; i < index; ++i)
cin >> array[i];
cout << checkMinimum(array, index) << endl;
}
int main()
{
int limit;
cin >> limit;
while(limit--)
getMinimum();
return 0;
}
在研究了 for 循环并尝试将它们合并在一起之后根本无济于事,因为很难将循环的条件满足为一个。
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;
int checkMinimum(int array[], int index)
{
int result = INT_MAX;
for(int i = 0, j = index - 1; i != j; ++i, --j)
if((min(result, ((array[i] & array[j]) ^ (array[i] | array[j]))) < result))
result = min(result, ((array[i] & array[j]) ^ (array[i] | array[j])));
return result;
}
void getMinimum()
{
int index;
cin >> index;
int array[index];
for(int i = 0; i < index; ++i)
cin >> array[i];
cout << checkMinimum(array, index) << endl;
}
int main()
{
int limit;
cin >> limit;
while(limit--)
getMinimum();
return 0;
}
那么我怎样才能降低这个的时间复杂度呢?
(array[i] & array[j]) ^ (array[i] | array[j])
等价于array[i] ^ array[j]
( &
, ^
, |
都是按位运算;写出真值表一点点)。
为了最小化异或,最重要的是高位一致。 假设输入有几个数字0xxxx
和几个数字1xxxx
。 尝试使用0xxxx
和1xxxx
的配对是没有意义的; 即使xxxx
部分完全相同,异或也是10000
,而任何0xxxx
与任何0xxxx
的异或,或任何1xxxx
与任何1xxxx
的异或最多为01111
,小于10000
。
在每个组中的下一位重复此逻辑,之后的下一位,可以显示具有最小 XOR 的对以排序顺序彼此相邻出现。 因此,您可以对数组进行排序并计算n − 1
相邻对的最小值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.