百练 / 2017研究生推免上机考试 G:Eqs

题目来源:http://poj.org/problem?id=1840

----------------------------------------

Eqs

总时间限制: 5000ms     内存限制: 65536kB

描述

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 theequation, xi
[-50,50], xi != 0,any i{1,2,3,4,5}.

Determine how many solutions satisfy the given equation.

输入

The only line of input contains the 5 coefficients a1,a2, a3, a4, a5, separated by blanks.

输出

The output will contain on the first line the number ofthe solutions for the given equation.

样例输入

37 29 41 43 47

样例输出

654

-----------------------------------------------------

解题思路

把等式改成 a1x13 + a2x23 + a3x33 = -a4x43 - a5x53

遍历复杂度由O(n5)下降为O(n3)

把计算结果存在数组里,两次计算结果匹配计数

-----------------------------------------------------

代码

#include
using namespace std;

const int MAX_RESULT = 25000000;// 化成两边之后右边两项之和最大就是2*50**4,最小就是-2*50**4

short Hash[MAX_RESULT+1] = {0};						// 不能放在main函数里
// 放在main函数里就是局部变量,放在栈里,会stack overflow
// 要用int,不能用short,用int会超内存

int main()
{
	int a[5] = {0};
	int i = 0;
	for (i=0; i<5; i++)
	{
		cin >> a[i];
	}
	
	int compute = 0;							// 中间计算结果
	int x0,x1,x2,x3,x4;							// 未知数
	int cnt = 0;								// 解的个数
	for (x0=-50; x0<=50; x0++)
	{
		if (x0 != 0)
		{
			for (x1=-50; x1<=50; x1++)
			{
				if (x1 != 0)
				{
					for (x2=-50; x2<=50; x2++)
					{
						if (x2 != 0)
						{
							compute = a[0]*x0*x0*x0 + a[1]*x1*x1*x1 + a[2]*x2*x2*x2;
							if (compute<0)		// 如果有负的,就加62500000变成正的
							{
								compute += MAX_RESULT;
							}
							Hash[compute]++;
						}
					}
				}
			}
		}
	}
	for (x3=-50; x3<=50; x3++)
	{
		if (x3 != 0)
		{
			for (x4=-50; x4<=50; x4++)
			{
				if (x4 != 0)
				{
					compute = -a[3]*x3*x3*x3 - a[4]*x4*x4*x4;
					if (compute<0)
					{
						compute += MAX_RESULT;
					}
					cnt += Hash[compute];
				}
			}
		}
	}
	cout << cnt;
	return 0;
}


你可能感兴趣的:(百练OJ/poj)