查找多维数据集对-(C ++中的(n ^(2/3)解决方案)
给出一个数字。我们必须找到两对,它们可以将数字表示为两个立方体的总和。所以我们必须找到两对(a,b)和(c,d),这样给定的数n可以表示为n=a3+b3=c3+d3
这个想法很简单。在这里,每个数字a,b,c和d都小于n1/3。对于每个小于n1/3的数字形成的不同对(x,y),如果它们的和(x3+y3)等于给定的数字,则将它们存储在哈希表中,并将和值作为键,然后如果再次获得相同的总和,他们只需打印每对
算法
getPairs(n):
begin
cube_root := cube root of n
map as int type key and pair type value
for i in range 1 to cube_root, do
for j in range i + 1 to cube_root, do
sum = i3 + j3 if sum is not same as n, then skip next part, go to second iteration
if sum is present into map, then print pair, and (i, j),
else insert (i,j) with corresponding sum into the map
done
done
end示例
#include <iostream>
#include <cmath>
#include <map>
using namespace std;
int getPairs(int n){
int cube_root = pow(n, 1.0/3.0);
map<int, pair<int, int> > my_map;
for(int i = 1; i<cube_root; i++){
for(int j = i + 1; j<= cube_root; j++){
int sum = i*i*i + j*j*j;
if(sum != n)
continue;
if(my_map.find(sum) != my_map.end()){
cout << "(" << my_map[sum].first << ", " << my_map[sum].second << ") and (" << i << ", " << j << ")" << endl;
}else{
my_map[sum] = make_pair(i, j);
}
}
}
}
int main() {
int n = 13832;
getPairs(n);
}输出结果
(2, 24) and (18, 20)
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬