poj 1840 Eqs(暴力枚举+hash)

题目链接

                                                                                                                    Eqs
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 13405   Accepted: 6583

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

题解:将问题分为两半来枚举。先枚举x1,x2的值,统计出a1x1^3+a2x2^3的所有值(由于值太大这里要用到hash)。再枚举x3,x4,x5的值,统计答案即可。复杂度O(10^6)

代码如下:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<string.h>
#include<map>
#define inff 0x3fffffff
#define nn 1100000
#define mod 1000003
typedef __int64 LL;
typedef unsigned __int64 LLU;
const LL tem=131313131;
using namespace std;
int a[6];
bool use[nn];
int num[nn];
int ha[nn];
void add(int x)
{
    int ix=(x%mod+mod)%mod;
    for(int i=ix;;i=(i+1)%mod)
    {
        if(!use[i])
        {
            use[i]=true;
            ha[i]=x;
            num[i]++;
            break;
        }
        else if(ha[i]==x)
        {
            num[i]++;
            break;
        }
    }
}
int Hash(int x)
{
    int ix=(x%mod+mod)%mod;
    for(int i=ix;;i=(i+1)%mod)
    {
        if(!use[i])
        {
            return -1;
        }
        else if(ha[i]==x)
            return i;
    }
    return -1;
}
int main()
{
    int i,j,k;
    int ix;
    while(scanf("%d%d%d%d%d",&a[1],&a[2],&a[3],&a[4],&a[5])!=EOF)
    {
        memset(num,0,sizeof(num));
        memset(use,false,sizeof(use));
        for(i=-50;i<=50;i++)
        {
            if(i==0)
                continue;
            for(j=-50;j<=50;j++)
            {
                if(j==0)
                    continue;
                ix=a[1]*i*i*i+a[2]*j*j*j;
                add(ix);
            }
        }
        LL ans=0;
        int tem;
        for(i=-50;i<=50;i++)
        {
            if(i==0)
                continue;
            for(j=-50;j<=50;j++)
            {
                if(j==0)
                    continue;
                for(k=-50;k<=50;k++)
                {
                    if(k==0)
                        continue;
                    ix=a[3]*i*i*i+a[4]*j*j*j+a[5]*k*k*k;
                    tem=Hash(-ix);
                    if(tem!=-1)
                        ans+=num[tem];
                }
            }
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(枚举,hash,ACM)