1. 程式人生 > >構建雜湊表——優化暴力求解方程

構建雜湊表——優化暴力求解方程

/*
 Consider equations having the following form: a*(x1)^2+b*(x2)^2+c*(x3)^2+d*(x4)^2=0
   a, b, c, d are integers from the interval [-50,50] and any of them cannot be 0.
 It is consider a solution a system (x1,x2,x3,x4)that verifies the equation, xi is an integer from
   [-100,100] and xi != 0, any i ∈{1,2,3,4}.
 Determine how many solutions satisfy the given equation.
 */

#include <bits/stdc++.h>
using namespace std;
int hash[2000003];
int main()
{
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    if((a>0 && b>0 && c>0 && d>0) || (a<0 && b<0 && c<0 && d<0))
    {
        cout << 0 << endl;
        return 0;
    }
    int pow2[101];
    for (int i = 1; i < 101; ++i) {
        pow2[i] = i*i;
    }
    memset(hash, 0, sizeof(hash));
    for (int i = 1; i < 101; ++i) {
        for (int j = 1; j < 101; ++j) {
            hash[a*pow2[i]+b*pow2[j]+1000000]++;
        }
    }
    int res = 0;
    for (int i = 1; i < 101; ++i) {
        for (int j = 1; j < 101; ++j) {
            res += hash[-c*pow2[i]-d*pow2[j]+1000000];
        }
    }
    cout << res*16 << endl;
    return 0;
}