【哈希】四平方和——第七届蓝桥杯省赛C++A/B组

#include <iostream>
#include <cstring>

using namespace std;

const int N = 5000010;

int n;
int C[N], D[N];

int main()
{
    scanf("%d", &n);
    
    memset(C, -1, sizeof C);
    for (int c = 0; c * c <= n; c ++ )
        for (int d = c; d * d + c * c <= n; d ++ )
        {
            int s = c * c + d * d;
            if (C[s] == -1)
                C[s] = c, D[s] = d;
        }
        
    for (int a = 0; a * a <= n; a ++ )
        for (int b = a; b * b + a * a <= n; b ++ )
        {
            int s = n - a * a - b * b;
            if (C[s] != -1)
            {
                printf("%d %d %d %d
", a, b, C[s], D[s]);
                return 0;
            }
        }
    return 0;
}
#include #include using namespace std; const int N = 5000010; int n; int C[N], D[N]; int main() { scanf("%d", &n); memset(C, -1, sizeof C); for (int c = 0; c * c <= n; c ++ ) for (int d = c; d * d + c * c <= n; d ++ ) { int s = c * c + d * d; if (C[s] == -1) C[s] = c, D[s] = d; } for (int a = 0; a * a <= n; a ++ ) for (int b = a; b * b + a * a <= n; b ++ ) { int s = n - a * a - b * b; if (C[s] != -1) { printf("%d %d %d %d ", a, b, C[s], D[s]); return 0; } } return 0; }
经验分享 程序员 微信小程序 职场和发展