二分搜索的思想来优化
O(n^3)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10005;
int k[N];
int binary_search(int x)
{
int l = 0, r = 10000;
while (l < r)
{
int mid = l + r >> 1;
if (mid * mid < x)
l = mid + 1;
else if (mid * mid == x)
return mid;
else if (mid * mid > x)
r = mid;
}
return -1;
}
int main()
{
int n;
cin >> n;
//n^3 logn
int kk = 0;
for(int i=0;i*i<=n;i++)
for(int j=0;j*j<=n;j++)
for (int k = 0;k * k <= n;k++)
{
int x = n - i * i - j * j - k * k;
int kk = binary_search(x);
if (kk == -1) continue;
else
{
cout << i << ' ' << j << ' ' << k << ' ' << kk;
exit(0);
}
}
return 0;
}
O(n^2log n)
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 2500100; //记得开大一点,否则答案会出错
//因为按照data排序后,可能0 4000 这个数在很后面,数组越界+wa
struct p
{
int x, y;
int data;
bool operator <(const p& b)const
{
if (data == b.data)
return x < b.x ? true : false;
return data < b.data ? true : false;
}
}k[N];
int cnt = 0;
//返回下标
int Binary_search(int c)
{
int l = 0, r = cnt - 1;
while (l < r)
{
int mid = l + r >> 1;
if (k[mid].data < c)
l = mid + 1;
if (k[mid].data >= c)
r = mid;
}
return k[l].data == c ? l : -1;
}
int main()
{
int n;
cin >> n;
for(int i=0;i * i <=n;i++)
for (int j = i;j * j+i*i<= n;j++)
{
k[cnt++] = { i,j,i * i + j * j };
}
sort(k, k + cnt);
for (int i = 0;i * i <= n;i++)
for (int j = 0;j * j+ i*i <= n;j++)
{
int c = n - i * i - j * j;
int l = 0, r = cnt - 1;
while (l < r)
{
int mid = l + r >> 1;
if (k[mid].data < c)
l = mid + 1;
if (k[mid].data >= c)
r = mid;
}
if (k[l].data != c) continue;
int x = k[l].x;
int y = k[l].y;
cout << i << ' ' << j << ' ' << x << ' ' << y << ' ';
exit(0);
}
}