Question in http://poj.org/problem? Id = 1840
InAlgorithmAs a beginner in the field, it is difficult for me to quickly extract specific problem models and find a suitable data structure. This is an example.
We have the following equations.
a1x1 3 + a2x2 3 +
a3x3 3 + a4x4 3 +
a5x5 3 = 0
Enter a set of coefficients and ask the number of solutions that are not equal to X1 X2 X4 X5. The input coefficient is in [-50, 50], and the solution range is also in [-50, 50].
At first glance, it must be a brute-force search. The time complexity is O (n ^ 5). You don't have to think about it. It must have timed out.
however, you can convert the problem to a1x1 3 +
a2x2 3 + a3x3 3 =< br>-(a4x4 3 + a5x5 3 )
Traverse the equations on the left, record the results in the hash table, traverse the equations on the right, and search in the hash table. Efficiency reduced to O (N ^ 3)
The value range of the leftmost equation is [-50 ^ 4*3, 50 ^ 4*3], because the IDs in the hash table cannot have plural numbers, therefore, the hash table size should be 50 ^ 4*3*2
However, I still don't understand this question.CodeAfter MLE is used, it is OK to remove it. Isn't it because the environment on sever won't let me look at the large array such as memset?
# Include <stdio. h> # include <memory. h> # define Max 18750000 short hash [Max * 2 + 100]; int main () {short coeff [5]; short I, J, K; int result; int sum = 0; scanf ("% d", coeff, coeff + 1, coeff + 2, coeff + 3, coeff + 4 ); {// memset (hash, 0, sizeof (hash); for (I =-50; I <= 50; I ++) {for (j =-50; j <= 50; j ++) {for (k =-50; k <= 50; k ++) {if (I! = 0 & J! = 0 & K! = 0) {result = I * coeff [0] + J * j * coeff [1] + K * coeff [2]; result + = max; hash [Result] ++ ;}}} sum = 0; for (I =-50; I <= 50; I ++) {for (j =-50; j <= 50; j ++) {if (I! = 0 & J! = 0) {result =-(I * coeff [3] + J * j * coeff [4]); Result + = max; sum + = hash [Result] ;}} printf ("% d \ n", sum);} return 0 ;}