POJ 1840 Eqs

来源:互联网 发布:php管理系统 编辑:程序博客网 时间:2024/06/14 15:45

Description
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 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
题意:
给定a1,a2,a3,a4,a5,求等式a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0 解的个数
分析:
由于是X的三次方,开方后不一定有解,所以不用二分搜索算法
本题若直接五重循环会超时,因此将等式分为左右两部分,即a1x13+ a2x23+ a3x33=-a4x43- a5x53,计算*项数少*的一边的和i(否则会超时),存入map,然后循环计算另一边的和d,看map中是否有d。

代码一:

#include <iostream>#include <map>using namespace std;int main(){    map<int,int> m;//定义一个名为m的map    map<int,int> :: iterator it;//定义一个map的迭代器    int i,d,a1,a2,a3,a4,a5,x,y,z,u,v,sum=0;    cin>>a1>>a2>>a3>>a4>>a5;    for(u=-50;u<=50;u++)    {        for(v=-50;v<=50;v++)        {            if(u!=0&&v!=0)            {            i=-a4*u*u*u-a5*v*v*v;                m[i]++;//存入map,first=i,second=1            }        }    }    for(x=-50;x<=50;x++)    {        for(y=-50;y<=50;y++)        {            for(z=-50;z<=50;z++)            {                if(x!=0&&y!=0&&z!=0)                {                    d=a1*x*x*x+a2*y*y*y+a3*z*z*z;                    it=m.find(d);//在map中查找d                    if(it!=m.end())                    {                        sum+=it->second;                    }                }            }        }    }    cout<<sum<<endl;    return 0;}

代码二:
(面向对象,标准格式)

#include<iostream>#include<map>using namespace std;class Eqs{private:    int a[5];    int cnt;private:    int Lfun(int x, int y, int z){return a[0]*x*x*x + a[1]*y*y*y + a[2]*z*z*z;}    int Rfun(int x, int y){return -a[3]*x*x*x - a[4]*y*y*y;}public:    void initial(){cnt = 0;}    bool readCase(){return cin >> a[0] >> a[1] >> a[2] >> a[3] >> a[4];}    void computing();    void outResult(){cout << cnt << endl;}};void Eqs::computing(){    map<int, int> m;    map<int, int>::iterator it;    for(int x = -50; x <= 50; x++){        for(int y = - 50; y <= 50; y++){            if(x!=0 && y!=0)                m[Rfun(x, y)]++;        }    }    for(int x = -50; x <= 50; x++){                for(int y = - 50; y <= 50; y++){            for(int z = -50; z <= 50; z++){                if(x!=0 && y!=0&& z!=0){                    it = m.find(Lfun(x, y, z));                    if(it != m.end()){                        cnt += it->second;                    }                }            }        }   } }int main(){    Eqs e;    while(e.readCase()){        e.initial();        e.computing();        e.outResult();    }    return 0;}