蓝桥杯——四平方和

版权声明:[email protected] https://blog.csdn.net/lytwy123/article/details/84639912

1.问题描述:



2.算法分析:

这道题目简单粗暴,枚举暴力算法,但是你不能死死的写四个for循环去判断,适当的剪枝会使得你的程序跑起来更快,并且需要注意不要你输出全部的组合,只要输出按照字典序排序输出。什么是字典序?这么说吧在这里比较的就是你的ASCALL值把,0的比1小,字母a比A大,所以你枚举只需要输出最小的能满足条件的a,b,c,d就要跳出所有循环了。
如果不是只求出字典序最小的组合,那你肯定超时,
就算你剪枝O(n^3)差不多了,你的数据是5000000(500w)你放进大O算一下,普通计算机CPU 1s能计算10^9次,你这肯定超了,所以这道题目找到第一个符合条件的就跳出。


3.源代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;

int main(){
   	int n , d;
    scanf("%d", &n);
    for (int a  = 0 ; a * a <= n ; a++){
        for (int b = 0 ; a * a + b * b <= n; b++){
            for (int c = 0 ; a * a + b * b + c * c <= n ; c++){
                d = sqrt(n - a *a - b * b - c * c);
                if (a * a + b * b + c * c + d * d == n){
                    printf("%d %d %d %d\n", a , b , c , d);
                    return 0;
                }
            }
        }
    }
    return 0;
}

欢迎关注Blog:http://47.107.118.184

猜你喜欢

转载自blog.csdn.net/lytwy123/article/details/84639912
今日推荐