1221. 四平方和

题目链接

1221. 四平方和

求一个数表示为 \(4\) 个非负整数的平方和的最小表示

输入格式

输入一个正整数 \(N\)

输出格式

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

数据范围

\(0<N<5∗10^6\)

输入样例:

5

输出样例:

0 0 1 2

哈希

用哈希存储两数的平方和,然后再枚举最小的两个数 \(i,j\),当 \(n-i*i-j*j\) 存在时即为答案,另外注意unordered_map常数大会超时,需要用数组模拟哈希表

  • 时间复杂度:\(O(n^2)\)

代码

// Problem: 四平方和
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1223/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=5e6+5;
PII mp[N];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<=n;i++)mp[i]={-1,-1};
	for(int i=0;i*i<=n;i++)
    	for(int j=i;j*j+i*i<=n;j++)
    		if(mp[i*i+j*j]==mkp(-1,-1))mp[i*i+j*j]={i,j};
    for(int i=0;i*i<=n;i++)
    	for(int j=i;j*j+i*i<=n;j++)
    		if(mp[n-i*i-j*j]!=mkp(-1,-1))
    		{
    			printf("%d %d %d %d",i,j,mp[n-i*i-j*j].fi,mp[n-i*i-j*j].se);
    			return 0;
    		}
    return 0;
}
posted @ 2022-02-22 11:42  zyy2001  阅读(23)  评论(0编辑  收藏  举报