http://poj.org/problem?id=1840
题意 : 有这样一个式子a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0,给你五个系数的值,让你找出x1,x2,x3,x4,x5的值满足这个式子,满足这个式子的方案有多少种输出
思路 : 这个题的话我一开始想的就是暴搜,五个for循环,但肯定会超时啊,问了会神才知道,原来这个题变通一下就行了,既然五个for循环超时那就分开,两个和三个,a1x13+ a2x23+ a3x33= -(a4x43+ a5x53),这样去搜就可以了,哈希表存一下,还有,这个的话,若x4和x5系数和x都是50,那么50*50*50*50+50*50*50*50就等于1250万,再加上负数,所以数组就要开到2500万,用int就会超内存,唉,多么痛的领悟啊!我交了两遍呢,所以用short定义
#include<cstdio> #include<cstring> #include<iostream> using namespace std ; const int maxn = 25000000; short ch[maxn] ; int main() { int a,b,c,d,e ; scanf("%d %d %d %d %d",&a,&b,&c,&d,&e); int sum = 0 ; memset(ch,0,sizeof(ch)); for(int x1 = -50 ; x1 <= 50 ; x1++) { if( x1 == 0) continue ; for(int x2 = -50 ; x2 <= 50 ; x2++) { if(x2 == 0) continue ; for(int x3 = -50 ; x3 <= 50 ; x3++) { if(x3 == 0) continue ; sum = a*x1*x1*x1+b*x2*x2*x2+c*x3*x3*x3 ; if(sum < 0) sum += maxn ; ch[sum] ++ ; } } } int count = 0 ; for(int x4 = -50 ; x4 <= 50 ; x4++) { if(x4 == 0) continue ; for(int x5 = -50 ; x5 <= 50 ; x5++) { if(x5 == 0) continue ; sum = d*x4*x4*x4+e*x5*x5*x5 ; if(sum < 0) sum += maxn ; count += ch[sum] ; } } printf("%d ",count) ; return 0 ; }
#include<cstdio> #include<cstring> #include<algorithm> #include<map> #define MAXN 25000001 using namespace std; int main() { int a1,a2,a3,a4,a5; scanf("%d%d%d%d%d",&a1,&a2,&a3,&a4,&a5); map<int,int>q; for(int x1=-50; x1<=50; x1++) { if(!x1) continue; for(int x2=-50; x2<=50; x2++) { if(!x2) continue; int sum=a1*x1*x1*x1+a2*x2*x2*x2; if(q.find(sum)==q.end()) q.insert(pair<int,int>(sum,1)); else q[sum]++; } } int ans=0; for(int x3=-50; x3<=50; x3++) { if(!x3) continue; for(int x4=-50; x4<=50; x4++) { if(!x4) continue; for(int x5=-50; x5<=50; x5++) { if(!x5) continue; int sum=a3*x3*x3*x3+a4*x4*x4*x4+a5*x5*x5*x5; if(q.find(sum)==q.end()) continue; ans+=q[0-sum]; } } } printf("%d ",ans); return 0; }
下面这个是会神用map写的