STL里的hash表会超时
自己手写的 ac了
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 5000010;
int main() {
int n;
scanf("%d", &n);
PII m[N];
memset(m, -1, sizeof m);
for(int i=0; i * i <= n; ++i) {
for(int j=i; i * i + j * j <= n; ++j) {
int x = i * i + j * j;
if(m[x].first == -1) m[x] = {i, j};
}
}
for(int i=0; i * i <= n; ++i) {
for(int j=i; i * i + j * j <= n; ++j) {
int x = n - i * i - j * j;
if(m[x].first != -1) {
printf("%d %d %d %d\n", i, j, m[x].first, m[x].second);
return 0;
}
}
}
return 0;
}
二分
查找最左边满足条件 二分中需写成a[mid] >= s
#include <bits/stdc++.h>
using namespace std;
const int N = 5000010;
int n, m;
struct Sum {
int s, c, d;
bool operator < (Sum& t) const {
if(s != t.s) return s < t.s;
if(c != t.c) return c < t.c;
return d < t.d;
}
}sum[N];
int main() {
scanf("%d", &n);
for(int c=0; c * c <= n; ++c) {
for(int d=c; c * c + d * d <= n; ++d){
int s = c * c + d * d;
sum[m++] = {s, c, d};
}
}
sort(sum, sum + m);
for(int a=0; a * a <= n; ++a) {
for(int b=a; a * a + b * b <= n; ++b) {
int s = n - a * a - b * b;
int l = 0, r = m - 1;
while(l < r) {
int mid = l + r >> 1;
if(sum[mid].s >= s) r = mid;
else l = mid + 1;
}
if(sum[r].s == s) {
printf("%d %d %d %d", a, b, sum[l].c, sum[l].d);
return 0;
}
}
}
return 0;
}