poj1840 map + hash

题意:输入五个范围在-50~50的系数,求一个五元三次方程有多少组解,解的范围也是-50~50。

做法:遍历方程的前两项,将值存到hash表中,再遍历后三项,看得到的值的相反数是否在hash表中。

我用map   hash,效率较低。

#include <iostream>
#include <map>
using namespace std;
typedef map < int, int > M_TYPE;

const int n = 50;

int cal(int x)
{
    return x * x * x;
}

int main()
{
    int c[5], i, j, k, key, ans = 0;

    M_TYPE mymap;
    M_TYPE::iterator it;
    for (i = 0; i < 5; i++)
        cin >> c[i];
    for (i = -1 * n; i <= n; i++){
        if (i == 0) continue;
        for (j = -1 * n; j <= n; j++){
             if (j == 0) continue;
             key = c[0] * cal(i) + c[1] * cal(j);
             it = mymap.find(key);
             if (it == mymap.end())
                 mymap.insert(make_pair(key, 1));
             else it->second++;
        }
    }
    for (i = -1 * n; i <= n; i++){
        if (i == 0) continue;
        for (j = -1 * n; j <= n; j++){
            if (j == 0) continue;
            for (k = -1 * n; k <= n; k++){
                 if (k == 0) continue;
                 key = - c[2] * cal(i) - c[3] * cal(j) - c[4] * cal(k);
                 it = mymap.find(key);
                 if (it != mymap.end())
                     ans += it->second;
            }
        }
    }
    cout << ans << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值