POJ-1840 Eqs (5元3次方程整数解的个数)

Consider equations having the following form: 
a1x1 3+ a2x2 3+ a3x3 3+ a4x4 3+ a5x5 3=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

思路1:把后两项移到右边,求出方程右边所有可能的值并排序。然后遍历求方程左边的值,二分查找是否有右边的值与它相等,有的话就加上与它相等的右边值的个数。(空间占用小,时间有点长~,但是能过)

一开始是想用散列存,这样可以直接判断有没有相等的值以及有多少个,然而超空间了

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
ll a[10];
ll p[105];
ll s[5];
ll y[15000],t=0;
int find(ll x){
	int l=0,r=t-1,mid;
	while(l<=r){
		mid=(l+r)>>1;
		if(y[mid]<x) l=mid+1;
		else if(y[mid]>x) r=mid-1;
		else{
			int ans=0;
			int cnt=mid;
			while(y[cnt]==x){     //往左找相等的值
				ans++;
				cnt--;
			}
			cnt=mid+1;
			while(y[cnt]==x){    //往右找相等的值
				ans++;
				cnt++;
			}
			return ans;
		}
	}
	return 0;
} 
int main() {
	for(int i=-50; i<=50; i++)
		p[i+50]=(ll)pow(i,3);
	for(int i=1; i<=5; i++)
		scanf("%lld",&a[i]);
	a[4]*=-1;
	a[5]*=-1;
	for(int i=-50; i<=50; i++) {
		if(i==0) continue;
		s[1]=a[4]*p[i+50];
		for(int j=-50; j<=50; j++) {
			if(j==0) continue;
			ll ans=s[1]+a[5]*p[j+50];
			y[t++]=ans;
		}
	}
	sort(y,y+t);
	ll ans=0;
	for(int i=-50;i<=50;i++){
		if(i==0) continue;
		s[1]=a[1]*p[i+50];
		for(int j=-50;j<=50;j++){
			if(j==0) continue;
			s[2]=s[1]+a[2]*p[j+50];
			for(int k=-50;k<=50;k++){
				if(k==0) continue;
				ll x=s[2]+a[3]*p[k+50];
				if(x>=-12500000&&x<=12500000)
				ans+=find(x);
			}
		}
	}
	printf("%lld\n",ans);
	return 0;
}

思路2:用散列存,不过数据类型用short(空间换时间,用short不会超空间,short占2个字节,int占4个字节,long long占8个字节)

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
int a[10];
int p[105];
int s[5];
int m=12500000;
short y[25000005];
int main() {
	for(int i=-50; i<=50; i++)
		p[i+50]=(int)pow(i,3);
	for(int i=1; i<=5; i++)
		scanf("%d",&a[i]);
	a[4]*=-1;
	a[5]*=-1;
	for(int i=-50; i<=50; i++) {
		if(i==0) continue;
		s[1]=a[4]*p[i+50];
		for(int j=-50; j<=50; j++) {
			if(j==0) continue;
			int ans=s[1]+a[5]*p[j+50];
			y[ans+m]++;
		}
	}
	int ans=0;
	for(int i=-50;i<=50;i++){
		if(i==0) continue;
		s[1]=a[1]*p[i+50];
		for(int j=-50;j<=50;j++){
			if(j==0) continue;
			s[2]=s[1]+a[2]*p[j+50];
			for(int k=-50;k<=50;k++){
				if(k==0) continue;
				int x=s[2]+a[3]*p[k+50];
				if(x>=-12500000&&x<=12500000)
				ans+=y[x+m];
			}
		}
	}
	printf("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42936517/article/details/86514827