【题解】P5691 [NOI2001] 方程的解数

题目链接(洛谷)

题目大意

已知一个$n$元高次方程:

已知未知数$x_i\in [1,m](i\in[1,n])$。给定$n,m,k_i,p_i$,求方程的整数解数

$1 \le n \le 6, 1 \le m \le 150, \sum_{i=1}^n|k_im^{p_i}<2^{31}|$

分析

首先想到暴力搜索,枚举每个$x$的解,时间复杂度为$O(150^6)\approx O(10^{13})$,显然不可过。继续观察,发现其实分别枚举前$\lfloor n/2\rfloor $个未知数和后$\lfloor n/2\rfloor $个未知数的值即可,枚举第一部分未知数时将出现的值以及出现次数记录下来,枚举出第二部分的值后,直接找这个值的相反数在第一部分中出现了几次,最后将答案加上这个数即可。时间复杂度降为$O(2\times 150^3)\approx O(6e6)$

实现

深搜枚举答案,其中$x_i^{p_i}$用快速幂即可:

1
2
3
4
5
6
7
8
9
10
11
ll qp(ll a, ll b) {
ll base = a, res = 1;
while (b > 0) {
if (b & 1) {
res *= base;
}
base *= base;
b >>= 1;
}
return res;
}

由于枚举出来的值$<2^{31}$,我们需要使用哈希表统计次数:

1
2
3
4
5
6
7
8
9
ll has(ll x) {
ll res = x % mod;
if (res < 0) res += mod;
while (num[res] && book[res] != x) {
res++;
if (res == mod) res = 0;
}
return res;
}

最后附完整代码($1.18s, 77.00mb$):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<bits/stdc++.h>

using namespace std;
const int mod = 5000007;
#define ll long long
ll ans, n, m, k[200], p[200], num[5000008], book[5000008];


ll qp(ll a, ll b) {
ll base = a, res = 1;
while (b > 0) {
if (b & 1) {
res *= base;
}
base *= base;
b >>= 1;
}
return res;
}

ll has(ll x) {
ll res = x % mod;
if (res < 0) res += mod;
while (num[res] && book[res] != x) {
res++;
if (res == mod) res = 0;
}
return res;
}

void f(ll x, ll sum) {
if (x > n / 2) {
int p = has(sum);
num[p]++;
book[p] = sum;
return;
}
for (int i = 1; i <= m; i++) {
f(x + 1, sum + qp(i, p[x]) * k[x]);
}
}

void f2(ll x, ll sum) {
if (x > n) {
ans += num[has(-sum)];
return;
}
for (int i = 1; i <= m; i++) {
f2(x + 1, sum + qp(i, p[x]) * k[x]);
}
}

int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> k[i] >> p[i];
}
f(1, 0);
f2(n / 2 + 1, 0);
cout << ans;
return 0;
}