题目:四平方和
四平方和定理,又称为拉格朗日定理:
每个正整数都可以表示为至多 4 个正整数的平方和。
如果把 0 包括进去,就正好可以表示为 4 个数的平方和。
比如:
5
=
0
2
+
0
2
+
1
2
+
2
2
5=0 ^{2} +0 ^{2} +1 ^{2} +2 ^{2}
5=02+02+12+22
7
=
1
2
+
1
2
+
1
2
+
2
2
7=1 ^{2} +1 ^{2} +1 ^{2} +2 ^{2}
7=12+12+12+22
对于一个给定的正整数,可能存在多种平方和的表示法。
要求你对 4 个数排序:
0≤a≤b≤c≤d
并对所有的可能表示法按 a,b,c,d 为联合主键升序排列,最后输出第一个表示法。
输入格式
输入一个正整数 N。
输出格式
输出4个非负整数,按从小到大排序,中间用空格分开。
数据范围
0
<
N
<
5
∗
1
0
6
0<N<5∗10^{6}
0<N<5∗106
输入样例:
5
输出样例:
0 0 1 2
二分法
O(N2logN)
/*
题解:
1.直接暴力循环,将有约2200*2200*2200*2200次,,超过了一亿,即10的八次方,(题目时间要求为1s,cpu1s运算约为10的八次方次),一定会超时,所以最最多三个循环,一般是俩次循环
2.先将c和d存到数组中,后将剩下的a和b遍历出来,每次遍历检查数组中是否有满足条件的值,有就结束了
*/
#include<iostream>
#include<algorithm>
#include<math.h>
const int N=5017600;
using namespace std;
int n,i;
struct Sum
{
int s,c,d;
/*bool operator< (const Sum &t)const
{
if (s != t.s) return s < t.s;
if (c != t.c) return c < t.c;
return d < t.d;
}*/
};
struct Sum sum[N];
//自己写的cmp函数,先比较s,然后比较c,然后d
bool cmp(const Sum& x1,const Sum& x2)
{
if(x1.s!=x2.s) return x1.s<x2.s;
if(x1.c!=x2.c) return x1.c<x2.c;
return x1.d<x2.d;
}
//测试用,打印Sum中存储的元素值
/*
void print()
{
for(int m=0;m<i;m++)
{
cout<<"s:"<<sum[m].s<<" c:"<<sum[m].c<<" d:"<<sum[m].d<<endl;
}
}
*/
int main()
{
cin>>n;
//先将c和d存到数组中,用空间换时间
for(int c=0;c * c <= n;c++)
for(int d=c;d*d+c*c<=n;d++)
{
sum[i++]={c*c+d*d,c,d};
}
//将数组排序,用于二分查找
sort(sum,sum+i,cmp);
//print();
//将剩下的a和b遍历出来,每次遍历检查数组中是否有满足条件的值,有就结束了
for(int a=0;a*a<=n;a++)
for(int b=a;b*b+a*a<=n;b++)
{
int l=0,r=i-1;
int t=n-a*a-b*b;
while(l<r)
{
int mid=l+r>>1;
if(sum[mid].s>=t) r=mid;
else l=mid+1;
}
if(t==sum[l].s)
{
printf("%d %d %d %d",a,b,sum[l].c,sum[l].d);
return 0;
}
}
}
暴力做法
O(N3)
#include <iostream>
using namespace std;
int n;
int main()
{
cin >> n;
for (int a = 0; a * a <= n; a ++ )
for (int b = a; a * a + b * b <= n; b ++ )
for (int c = b; a * a + b * b + c * c <= n; c ++ )
{
int t = n - a * a - b * b - c * c;
int d = sqrt(t);
if (d * d == t)
{
printf("%d %d %d %d\n", a, b, c, d);
return 0;
}
}
}