美文网首页
蓝桥杯_四平方和(暴力枚举及二分优化)

蓝桥杯_四平方和(暴力枚举及二分优化)

作者: 掌灬纹 | 来源:发表于2019-03-16 14:43 被阅读0次

四平方和

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

每个正整数都可以表示为至多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 (N<5000000)

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

例如,输入:

5

则程序应该输出:

0 0 1 2

再例如,输入:

12

则程序应该输出:

0 2 2 2

再例如,输入:

773535

则程序应该输出:

1 1 267 838

资源约定:

峰值内存消耗(含虚拟机) < 256M

CPU消耗  < 3000ms

二分优化思路:记录前两个数的平方和,枚举+二分查找(n - c*c-d*d)

注意 下标的控制 值得一提的该题类似于挑战程序设计竞赛一书中的抽签问题优化 有兴趣的可以了解一下

import java.util.Arrays;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int t = (int) Math.sqrt(n);

f1(n, t);//暴力枚举

//f2(n, t);//二分 + 枚举(四部分两两考虑)

}

private static void f2(int n, int t) {

int[] sum = new int [(t+1)*(t+1)];

for(int a = 0; a <= t; a++) {

for(int b = 0; b <= t; b++) {//前两个数的和统计起来

sum[a*(t+1) + b] = a*a + b*b;

}

}

for(int c = t; c >= 0; c--) {

for(int d = t; d >= 0; d--) {//小技巧

int index = Arrays.binarySearch(sum, n - c * c - d * d);

if(index >= 0) {

//System.out.println(index);

System.out.println((int)Math.sqrt(index - index%(t+1)) + " " +

index%(t+1) + " " + d +" " + c);

System.exit(0);

}

}

}

}

private static void f1(int n, int t) {

for(int a = 0; a <= t; a++) {

for(int b = 0; b <= t; b++) {

for(int c = 0; c <= t; c++) {

for(int d = t; d >= 0; d--) {

if(a*a + b*b + c*c + d*d == n) {

System.out.println(a + " " + b + " " + c + " " + d);

System.exit(0);

}

}

}

}

}

}

}

相关文章

网友评论

      本文标题:蓝桥杯_四平方和(暴力枚举及二分优化)

      本文链接:https://www.haomeiwen.com/subject/owcsmqtx.html