栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

蓝桥杯-四平方和

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

蓝桥杯-四平方和

四平方和定理,又称为拉格朗日定理:

每个正整数都可以表示为至多 4 个正整数的平方和。

如果把 0 包括进去,就正好可以表示为 4 个数的平方和。

对于一个给定的正整数,可能存在多种平方和的表示法。

要求你对 4 个数排序:

0≤a≤b≤c≤d

并对所有的可能表示法按 a,b,c,d为联合主键升序排列,最后输出第一个表示法。

输入格式:

输入一个正整数 N。

输出格式:

输出4个非负整数,按从小到大排序,中间用空格分开。

数据范围:

0

输入样例:

5

输出样例:

0 0 1 2

第一种方法:暴力破解。

即枚举三个数,第四个数为sqrt(n-a*a-b*b-c*c)。时间复杂度为O(n的三次方),易时间超限

#include
#include
using namespace std;

const int N=5000010;
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 %dn",a,b,c,d);
                    return 0;
                }
            }
        }
    }
}

第二种算法:用空间来换取时间(哈希算法) 

时间复杂度O(n的二次方*logN)

#include
#include//pair的头文件
#include

using namespace std;

#define x first//用x代替first
#define y second//用y代替second
const int N=5e6+10;//即5*10的6次方
int n;
pair s[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 t=c*c+d*d;
            if(s[t].x==0&&s[t].y==0)
            {
                s[t].x=c;
                s[t].y=d;
            }
        }
    }
    
    for(int a=0;a*a<=n;a++)
    {
        for(int b=a;b*b+a*a<=n;b++)
        {
            int t=n-a*a-b*b;
            if(s[t].y!=0){
                printf("%d %d %d %dn",a,b,s[t].x,s[t].y);
                return 0;
            }
        }
    }
    
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/767836.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号