poj 1840 Eqs
Description
Consider equations having the following form:
a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0
The coefficients are given integers from the interval [-50,50].
It is consider a solution a system (x1, x2, x3, x4, x5) that verifies the equation, xi∈[-50,50], xi != 0, any i∈{1,2,3,4,5}.
Determine how many solutions satisfy the given equation.
a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0
The coefficients are given integers from the interval [-50,50].
It is consider a solution a system (x1, x2, x3, x4, x5) that verifies the equation, xi∈[-50,50], xi != 0, any i∈{1,2,3,4,5}.
Determine how many solutions satisfy the given equation.
Input
The only line of input contains the 5 coefficients a1, a2, a3, a4, a5, separated by blanks.
Output
The output will contain on the first line the number of the solutions for the given equation.
Sample Input
37 29 41 43 47
Sample Output
654
大致题意就是给出一个5元3次方程,输入其5个系数,求它的解的个数。
其中系数 ai∈[-50,50] 自变量xi∈[-50,50],并且xi!=0。
思路:一开始是想直接暴力枚举求得,O(n^5),题目要求 Time Limit: 5000MS Memory Limit: 65536K,铁定超
后来用哈希,把公式变形-a1x13+ a2x23=a3x33+ a4x43+ a5x53
先左式求值打表,然后跟右侧进行比较。O(n^2)+ O(n^3)<=O(n^5)
注意:数组类型用 short,之前用的 int 内存超限
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 using namespace std; 5 short hash[25000005]; 6 int main() 7 { 8 int a[10]; 9 int count=0; 10 for(int i=1; i<=5; i++) 11 cin>>a[i]; 12 for(int i=-50; i<=50; i++) 13 { 14 if(i==0) 15 continue; 16 for(int j=-50; j<=50; j++) 17 { 18 if(j==0) 19 continue; 20 int tmp=i*i*i*a[1]+j*j*j*a[2]*-1; 21 if(tmp<0) 22 tmp+=25000000; 23 hash[tmp]++; 24 } 25 } 26 for(int i=-50; i<=50; i++) 27 { 28 if(i==0) 29 continue; 30 for(int j=-50; j<=50; j++) 31 { 32 if(j==0) 33 continue; 34 for(int k=-50; k<=50; k++) 35 { 36 if(k==0) 37 continue; 38 int tmp=i*i*i*a[3]+j*j*j*a[4]+k*k*k*a[5]; 39 if(tmp<0) 40 tmp+=25000000; 41 if(hash[tmp]) 42 count+=hash[tmp]; 43 } 44 } 45 } 46 cout<<count<<endl; 47 return 0; 48 }