POJ1840

来源:互联网 发布:360卸载找不到软件 编辑:程序博客网 时间:2024/06/05 12:45

1.题目描述:

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

2.题意概述:

给出一个5元3次方程,输入其5个系数,求它的解的个数

其中系数 ai∈[-50,50]  自变量xi∈[-50,0)∪(0,50]

 

注意:

  若x1 =a, x2=b ,x3=c ,x4=d,x5=e时,与 x1=b, x2=a ,x3=c ,x4 =d, x5=e 代入方程后都得到值0,那么他们视为不同的解。

3.解题思路:

对方程做一个变形


 

即先枚举x1和x2的组合,把所有出现过的 左值 记录打表,然后再枚举x3 x4 x5的组合得到的 右值,如果某个右值等于已经出现的左值,那么我们就得到了一个解

时间复杂度从 O(n^5)降低到 O(n^2+n^3),大约执行100W次

 

 

我们先定义一个映射数组hash[],初始化为0

对于方程左边,当x1=m  ,  x2= n时得到sum,则把用hash[]记录sum : hash[sum]++,表示sum这个值出现了1次

之所以是记录“次数”,而不是记录“是否已出现”,

是因为我们不能保证函数的映射为 1对1 映射,更多的是存在 多对1映射

例如当 a1=a2时,x1=m  ,  x2= n我们得到了sum,但x1=n  ,  x2= m时我们也会得到sum,但是我们说这两个是不同的解,这就是 多对1 的情况了,如果单纯记录sum是否出现过,则会使得 解的个数 减少。

 

其次,为了使得 搜索sum是否出现 的操作为o(1),我们把sum作为下标,那么hash数组的上界就取决于a1 a2 x1 x2的组合,四个量的极端值均为50

因此上界为 50*50^3+50*50^3=12500000,由于sum也可能为负数,因此我们对hash[]的上界进行扩展,扩展到25000000,当sum<0时,我们令sum+=25000000存储到hash[]

4.AC代码:

#include <cstdio>#include <iostream>#include <cstring>#include <string>#include <algorithm>#include <functional>#include <cmath>#include <vector>#include <queue>#include <map>#include <set>#include <ctime>#define INF 0x7fffffff#define maxn 18000008#define eps 1e-6#define pi acos(-1.0)#define e 2.718281828459#define mod (int)1e9 + 7;using namespace std;typedef long long ll;short hash[maxn * 2];int a1, a2, a3, a4, a5;int main(){#ifndef ONLINE_JUDGE  freopen("in.txt", "r", stdin);  freopen("out.txt", "w", stdout);  long _begin_time = clock();#endif  while (scanf("%d%d%d%d%d", &a1, &a2, &a3, &a4, &a5) != EOF)  {    ll ans = 0;    for (short i = -50; i <= 50; i++)    {      if (i == 0)        continue;      for (short j = -50; j <= 50; j++)      {        if (j == 0)          continue;        for (short k = -50; k <= 50; k++)        {          if (k == 0)            continue;          hash[i * i * i * a1 + j * j * j * a2 + k * k * k * a3 + maxn]++;        }      }    }    for (short i = -50; i <= 50; i++)    {      if (i == 0)        continue;      for (short j = -50; j <= 50; j++)      {        if (j == 0)          continue;        ans += hash[-i * i * i * a4 - j * j * j * a5 + maxn];      }    }    printf("%lld\n", ans);  }#ifndef ONLINE_JUDGE  long _end_time = clock();  printf("time = %ld ms\n", _end_time - _begin_time);#endif  return 0;}