HDU1407 测试你是否和LTC水平一样高

时间:2023-03-08 20:44:54

题目大意:给出一个num,计算方程x2+y2+z^2 = num的第一个正整数解(字典序),0 < num <= 10000。

方法参考了网上的博客,自己打了一波,发现还有很多不懂的地方。

方法1:直接对x、y、z枚举。

用goto跳出多重循环

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <malloc.h>
using namespace std; int main() {
int n;
int pow2[105];
for (int i = 1; i <= 100; i++) {
pow2[i] = i*i;
}
while(!cin.eof() && cin >> n) {
for (int a = 1; a <= 100; a++) {
for (int b = 1; b <= 100; b++) {
for (int c = 1; c <= 100; c++) {
if (pow2[a] + pow2[b] + pow2[c] == n) {
cout << a << " " << b << " " << c << endl;
goto end;
}
}
}
}
end:;
} return 0;
}

方法2:对x、y枚举,对z使用二分查找。

分清楚m和a[m],勿乱。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <malloc.h>
using namespace std; int binSearch(int* a, int tar) {
int l = 1;
int r = 101;
while(l < r) {
int m = l + (r - l) / 2; //写成int m = (l + r) / 2可能会爆
if (a[m] == tar) return m;
else if (a[m] < tar) l = m + 1;
else r = m;
}
return -1;
} int main() {
int n;
int pow2[105];
for (int i = 1; i <= 100; i++) {
pow2[i] = i*i;
}
while(!cin.eof() && cin >> n) {
for (int a = 1; a <= 100; a++) {
for (int b = 1; b <= 100; b++) {
int c = binSearch(pow2, n - pow2[a] - pow2[b]);
if (c != -1) {
cout << a << " " << b << " " << c << endl;
goto end;
}
}
}
end:;
} return 0;
}

方法3:对x、y枚举,对z用hash查找。

普通数组:用key找value。hash:用value找key。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <malloc.h>
using namespace std; struct Hash {
bool exist;
int key;
};
Hash h[10001]; //很多头文件都有hash,所以改成了h int main() {
int pow2[105];
for (int i = 1; i <= 100; i++) {
pow2[i] = i*i;
h[pow2[i]].exist = true;
h[pow2[i]].key = i;
}
int n;
while(~scanf("%d", &n)) {
for (int a = 1; a <= 100; a++) {
for (int b = 1; pow2[a] + pow2[b] <= n; b++) { //b <= 100写法错误,id会小于0
int id = n - pow2[a] - pow2[b];
if(h[id].exist) {
printf("%d %d %d\n", a, b, h[id].key);
goto end;
}
}
}
end:;
} return 0;
}