四平方和h

四平方和

ps:标题一定要满5个字这种要求就很迷,于是乎,字数不够,hhh来凑

前言:这题只有二分才能AC,其他都会超时555

题目

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

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

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

比如:

5=02+02+12+22
7=12+12+12+22

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

要求你对 4 个数排序:

0 ≤ a ≤ b ≤ c ≤ d

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

输入格式

输入一个正整数 N。

输出格式

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

数据范围

0 < N < 5∗106

输入样例:
5
输出样例:
0 0 1 2
分析

(通过分析时间复杂度判断要枚举几个数)
(1)最多只能枚举2个数
(2)because最暴力做法要枚举3个数,so用空间换时间
(下面是一些乱七八糟的笔记maybe只有我自己看得懂)
在这里插入图片描述

法一(暴力三重for循环TLE)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>

using namespace std;

const int N=2500010;

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;
				} 
			}
		}
	}
}
法二(二分AC)
理论上时间复杂度O(n2×㏒n)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>

using namespace std;

const int N=2500010;

struct Sum
{
	int s,c,d;//s表示c和d的平方
	bool operator<(const Sum &t)const 
	{
		if(s!=t.s)
		{
			return s<t.s;
		}
		if(c!=t.s)
		{
			return c<t.c;
		}
		return d<t.d;
	} 
}Sum[N];

int n,m;

int main()
{
	cin>>n;
	
	for(int c=0;c*c<=n;c++)
	{
		for(int d=c;c*c+d*d<=n;d++)
		{
			Sum[m++]={c*c+d*d,c,d};
			
		}
	}
	sort(Sum,Sum+m);
	
	for(int a=0;a*a<=n;a++)
	{
		for(int b=0;a*a+b*b<=n;b++)
		{
			int t=n-a*a-b*b;
			int l=0,r=m-1;
			while(l<r)
			{
				int mid=l+r>>1;
				if(Sum[mid].s>=t)
				{
					r=mid;
				}
				else
				{
					l=mid+1;
				}
			}
			if(Sum[l].s==t)
			{
				printf("%d %d %d %d\n",a,b,Sum[l].c,Sum[l].d);
				return 0;
			}
		}
	}
	return 0;
}
法三(哈希TLE)
理论上时间复杂度O(n2)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<unordered_map>

#define x first
#define y second

using namespace std;

typedef pair<int ,int> PII;

const int N=2500010;

int n,m;
unordered_map<int,PII> S;

int main()
{
	cin>>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.count(t)==0)
			{
				S[t]={c,d};
			}
			
		}
	}
	
	for(int a=0;a*a<=n;a++)
	{
		for(int b=0;a*a+b*b<=n;b++)
		{
			int t=n-a*a-b*b;
			if(S.count(t))
			{
				printf("%d %d %d %d\n",a,b,S[t].x,S[t].y);
				return 0;
			}
		}
	}
	return 0;
}
实际上这题哈希比二分慢
综上,实践出真知(狗头)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值