AcWing 1221. 四平方和

题目

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

每个正整数都可以表示为至多 4

个正整数的平方和。

如果把 0
包括进去,就正好可以表示为 4

个数的平方和。

比如:

5=02+02+12+22

7=12+12+12+22

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

要求你对 4

个数排序:

0≤a≤b≤c≤d

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

思路

在这里插入图片描述

二分做法

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2500010;
struct number{
    int s,c,d;
    bool operator < (const number& t){
        if (s != t.s) return s < t.s;
        if (c != t.c) return c < t.c;
        return d < t.d;
    }
}sum[N];
int main(){
    int n;
    cin >> n;
    int idx=0;
    for(int c=0;c*c<=n;c++){//先把所有的c,d枚举一遍
        for(int d=c;d*d+c*c<=n;d++){
            sum[idx++]={c*c+d*d,c,d};
        }
    }
    sort(sum,sum+idx);
            
    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 = idx - 1;
            while (l < r)//用二分取查找最左边的c,d,就是最小解
            {
                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;
            }
        }
}

哈希做法

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>

#define x first
#define y second
using namespace std;
const int N = 2500010;
typedef pair<int, int> PII;
int n, m;
unordered_map<int, PII> S;
int main(){
    cin >> n;
    int idx=0;
    for(int c=0;c*c<=n;c++){
        for(int d=c;d*d+c*c<=n;d++){
            if (S.count(d*d+c*c) == 0) S[d*d+c*c] = {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;
            int l = 0, r = idx - 1;
            if(S.count(t)){
                printf("%d %d %d %d\n", a, b,S[t].x, S[t].y);
                return 0;
                
            }
        }
}
发布了175 篇原创文章 · 获赞 1 · 访问量 4257

猜你喜欢

转载自blog.csdn.net/weixin_45080867/article/details/104048152
今日推荐