zoukankan      html  css  js  c++  java
  • 1221. 四平方和

    四平方和定理,又称为拉格朗日定理:每个正整数都可以表示为至多 4个正整数的平方和。如果把 0包括进去,就正好可以表示为 4个数的平方和。
    比如:
    (5=0^2+0^2+1^2+2^2)
    (7=1^2+1^2+1^2+2^2)
    对于一个给定的正整数,可能存在多种平方和的表示法。

    要求你对 4
    个数排序:
    (0≤a≤b≤c≤d)
    并对所有的可能表示法按 a,b,c,d为联合主键升序排列,最后输出第一个表示法。

    输入格式

    输入一个正整数 N

    输出格式

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

    数据范围
    (0<N<5∗10^6)
    输入样例:

    5
    输出样例:

    0 0 1 2

    方法

    三重循环是可以过的,但是也可以用二分来做,先枚举b和c,然后再枚举a和b,通过a,b和n算出t,用二分找出字典序最小的b,c,如果能找到说明可以,也可以用哈希表做。

    #include<iostream>
    #include<algorithm>
    
    using namespace std;
    
    const int N = 25000010;
    
    struct Sum{
        int s, c, d;
        bool operator<(const Sum &sum){
            if(s != sum.s) return s < sum.s;
            if(c != sum.c) return c < sum.c;
            return d < sum.d;
        }
    }sum[N];
    
    int n, cnt;
    
    int main(){
        cin >> n;
        
        for(int c = 0; c * c <= n; c ++)
            for(int d = c; c * c + d * d <= n; d ++)
                sum[cnt ++] = {c * c + d * d, c, d};
                
        sort(sum, sum + cnt);
        
        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;
                
                int l = 0, r = cnt - 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
    ", a, b, sum[l].c, sum[l].d); 
                    return 0;
                }
            }
    }
    
  • 相关阅读:
    python模块之datetime方法详细介绍
    练习十七:python辨别数据类型
    练习十六:Python日期格式应用(datetime)
    Tkinter的l组件常用属性
    Log4net使用方法
    Thinkphp中在本地测试很好,在服务器上出错,有可能是因为debug缓存的问题
    Git 常见问题
    Linq中的in和not in的使用方法
    网络协议
    WCF传输协议
  • 原文地址:https://www.cnblogs.com/tomori/p/13475110.html
Copyright © 2011-2022 走看看