POJ1186 方程的解数
题目连接:http://poj.org/problem?id=1186
Description
已知一个n元高次方程:
其中:x1, x2,…,xn是未知数,k1,k2,…,kn是系数,p1,p2,…pn是指数。且方程中的所有数均为整数。
假设未知数1 <= xi <= M, i=1,n,求这个方程的整数解的个数。
1 <= n <= 6;1 <= M <= 150。
方程的整数解的个数小于231。
★本题中,指数Pi(i=1,2,…,n)均为正整数。
Input
第1行包含一个整数n。第2行包含一个整数M。第3行到第n+2行,每行包含两个整数,分别表示ki和pi。两个整数之间用一个空格隔开。第3行的数据对应i=1,第n+2行的数据对应i=n。
Output
仅一行,包含一个整数,表示方程的整数解的个数。
Sample Input
3
150
1 2
-1 2
1 2
Sample Output
178
Source
Noi 01
分析:
这道题如果暴力枚举的话很显然会超时
150 ^ 6 = 11390625000000…
150 ^ 3 = 3375000,这是可以接受的
所以我们把方程分成两半,先搜索计算前一半,用hash将所有总值存储起来,再搜索后一半,然后看是否和左值相等,如果相等则是同一个解
解法一:hash + 乘法原理
解法二:存<结果,解数>二元组数组, 双指针扫描 + 乘法原理
时间复杂度都是O(M ^ (n/2) + M ^ (n/2))
这里提供解法一的代码
代码实现:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
const int hashlen = 1000023;
const int maxnodenum = 4000024;
inline int read()
{
char ch, c;
int res;
while (ch = getchar(), ch < '0' || ch < '9') c = ch;
res = ch - 48;
while (ch = getchar(), ch >= '0' && ch <= '9')
res = (res << 3) + (res << 1) + ch - 48;
if (c == '-') res = -res;
return res;
}
void write(int x)
{
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
int n, m, ans, e, tag;
int k[32], p[32];
int head[hashlen + 10];
struct node
{
int val;
int cnt;
int nxt;
}edge[maxnodenum + 10];
int hash_value(int x)
{
return x > 0 ? x % hashlen : x % hashlen + hashlen;
}
void insert(int x)
{
int y = hash_value(x);
for (int i = head[y]; i != -1; i = edge[i].nxt)
{
if (edge[i].val == x)
{
++edge[i].cnt;
return;
}
}
edge[e].val = x, edge[e].cnt = 1; edge[e].nxt = head[y], head[y] = e++;
}
int lookup (int x)
{
int y = hash_value(x);
for (int i = head[y]; i != -1; i = edge[i].nxt)
if (edge[i].val == x)
return edge[i].cnt;
return 0;
}
void dfs(int cur, int end, int sum)
{
if (cur == end)
{
if (tag == 0)
insert(sum);
else
ans += lookup(-sum);
return;
}
for (int i = 1; i <= m; ++i)
{
int t = 1;
for (int j = 0; j < p[cur]; ++j)
t *= i;
dfs(cur + 1, end, sum + k[cur] * t);
}
}
int main()
{
n = read();
m = read();
memset(head, -1, sizeof(head));
ans = e = 0;
for (int i = 0; i < n; ++i)
{
k[i] = read();
p[i] = read();
}
tag = 0;
dfs(0, n /2, 0);
tag = 1;
dfs(n / 2, n, 0);
write(ans);
return 0;
}