#include<bits/stdc++.h>
using namespace std;
#define int long long
int sum;
void sovel()
{
cin >> sum;
for (int a = 0; a <sum; a++)
{
for (int b = 0; b <sum; b++)
{
for (int c = 0; c <sum; c++)
{
for (int d = 0; d <sum; d++)
{
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
return 0;
}
}
}
}
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t = 1;
while(t--)
{
sovel();
}
return 0;
}
刚开始是这样写的,只能通过25%:
我们有四层循环,n最大是5e6,我们尽可能的去减少循环的层数,也就是减少变量。
第二,我们应该去枚举aa ,bb ,c*c,而不是去枚举a,b,c,d,这样可以更快的枚举到,也就减少了消耗。
#include<bits/stdc++.h>
using namespace std;
#define int long long
int sum;
int sovel()
{
cin >> sum;
for (int a = 0; a*a <sum ; a++)
{
for (int b = 0; a*a+b*b <sum ; b++)
{
for (int c = 0; a*a+b*b+c*c <= sum; c++)
{
int d = sqrt(sum - a*a - b*b - c*c);
if(a*a+b*b+c*c+d*d==sum)
{
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
return 0;
}
}
}
}
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t = 1;
while (t--)
{
sovel();
}
return 0;
}
但是实际上还是很慢:
在这里我们可以把c也去掉