三部曲一(数据结构)-1024-Eqs Eqs
解方程整数解的题,通过这道题我学会了这种题的一般做法,对于未知数较少、取值范围较小且解为整数的方程,把一半的未知数移到等式的另一边,然后对两边分别枚举,用哈希配对,如果有相同的结果就找到一组解。具体做法是先把一边的结果插入hash表,再把另一边的结果在hash表里查找。
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 16 Accepted Submission(s) : 9
Problem 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
Source
PKU
1 #include <iostream> 2 #include <stdio.h> 3 #include <cstring> 4 #include <stdlib.h> 5 #include <cmath> 6 #define seed 999983 7 #define inf 0x7fffffff 8 using namespace std; 9 10 struct Hash 11 { 12 int val,next; 13 }h[1000000]; 14 15 int cnt; 16 void Insert(int n) 17 { 18 int key=abs(n)%seed; 19 // cout<<key<<endl; 20 if(h[key].val==inf) //插入的位置没有值 21 h[key].val=n; 22 else //插入的位置已有值,冲突处理 23 { 24 int i,last; 25 for(i=key;i!=-1;i=h[i].next) 26 last=i; 27 i=last; 28 for(;h[i].val!=inf;i=(i+1)%1000000); 29 h[i].val=n; 30 h[last].next=i; 31 } 32 } 33 34 void check(int n) 35 { 36 int key=abs(n)%seed; 37 if(h[key].val==inf) 38 return; 39 else 40 { 41 int i; 42 for(i=key;i!=-1;i=h[i].next) 43 if(h[i].val==n) 44 { 45 // cout<<n<<' '<<h[i].val<<' '<<h[i].next<<endl; 46 cnt++; 47 } 48 return; 49 } 50 } 51 52 int main() 53 { 54 // freopen("in.txt","r",stdin); 55 int a1,a2,a3,a4,a5; 56 cnt=0; 57 scanf("%d%d%d%d%d",&a1,&a2,&a3,&a4,&a5); 58 int i,j,k; 59 memset(h,-1,sizeof(h)); 60 for(i=0;i<1000000;i++) 61 h[i].val=inf; 62 for(i=-50;i<=50;i++) 63 { 64 if(i==0) //注意未知数都不能为零 65 continue; 66 for(j=-50;j<=50;j++) 67 { 68 if(j==0) 69 continue; 70 int tmp=-(a1*i*i*i+a2*j*j*j); 71 // cout<<tmp<<endl; 72 Insert(tmp); 73 } 74 } 75 for(i=-50;i<=50;i++) 76 { 77 if(i==0) 78 continue; 79 for(j=-50;j<=50;j++) 80 { 81 if(j==0) 82 continue; 83 for(k=-50;k<=50;k++) 84 { 85 if(k==0) 86 continue; 87 int tmp=a3*i*i*i+a4*j*j*j+a5*k*k*k; 88 check(tmp); 89 } 90 } 91 } 92 printf("%d ",cnt); 93 return 0; 94 }