【POJ 1840 --- Eqs】

【POJ 1840 --- Eqs】


Description

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

  • 解题思路

显而易见通过暴力遍历5重for循环肯定会TLE。
为了减少遍历次数,我们可以将表达式改写一下:
即:-1*(a1x1^3+ a2x23)=a3x33+ a4x4^3+ a5x5^3;
改写后我们只需遍历一个双重for循环和一个三重for循环。大大缩短了运行时间。
通过数组arr标记左边的值temp(即arr[temp]++),当右边也等于该值时ans+1。
但是却出现一个问题:那就是数组该建多大的呢?
根据题意知505050502=12500000,即范围是-12500000到12500000,为了区分负数,当temp小于0时,我们将它标记到正数上,即创建一个25000000大小的数组,当temp<0时令temp+=25000000;
由于数组很大,必须使用全局定义
同时由于数组很大,用int定义必然会MLE,因此要用char或者short定义数组,推荐short

AC代码:

#include 
#include 
#include 
#include 
#define MAXN 25000010
using namespace std;
short arr[MAXN];
int main()
{
    int a1,a2,a3,a4,a5;
    int ans=0,temp;
    memset(arr,0,sizeof(arr));
    scanf("%d%d%d%d%d",&a1,&a2,&a3,&a4,&a5);
    for(int i=-50;i<=50;i++)
    {
        for(int j=-50;j<=50;j++)
        {
            if(i==0 || j==0)
                continue;
            temp = (a1*i*i*i+a2*j*j*j)*-1;
            if(temp<0)
                temp += MAXN;
            arr[temp]++;
        }
    }
    for(int i=-50;i<=50;i++)
    {
        for(int j=-50;j<=50;j++)
        {
            for(int k=-50;k<=50;k++)
            {
                if(i==0 || j==0 || k==0)
                    continue;
                temp = a3*i*i*i + a4*j*j*j + a5*k*k*k;
                if(temp<0)
                    temp+=MAXN;
                if(arr[temp])
                {
                    ans+=arr[temp];
                }
            }
        }
    }
    printf("%d\n",ans);

    return 0;
}

你可能感兴趣的:(ACM,POJ,1840,Eqs,POJ,1840,Eqs)