1. 程式人生 > >藍橋杯——四平方和

藍橋杯——四平方和

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