G:严肃古板的秩序

思路:暴力搜索,暴力搜索三种符号的情况,看是否有一种能符合题意,如果有,就return 1,否则就是return 0;这个题写的时候有几个坑点要注意一下:

1.定义a#b当且仅当a和b都是正整数时是有意义的。也就是说,在讨论#的时候,要先判断一下当前数和下一个数是否都大于0,才能递归下去

2.a^a%b,用快速幂写时,不要忘了先把a初始化为a%b,不然就会WA

代码:

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
using namespace std;
#define int long long
int a[100];
int ans;
char ch;
int cnt = 0;
char b[100];
int ksm(int a, int b, int p)
{
int ans = 1;
a = a % p;
while (b)
{
if (b & 1)
{
ans = ans * a % p;
}
b >>= 1;
a = a * a % p;
}
return ans % p;
}
int dfs(int x, int pos)
{
if (pos == cnt)
{
if (x == ans)
{
for (int i = 1; i <= cnt; i++)
{
if (i == cnt)
{
cout << a[cnt] << "=" << ans;
}
else
{
cout << a[i] << b[i];
}
}
cout << '\n';
return 1;
}
return 0;
}
b[pos] = '+';
if (dfs(x + a[pos + 1], pos + 1) == 1)
{
return 1;
}
b[pos] = '-';
if (dfs(x - a[pos + 1], pos + 1) == 1)
{
return 1;
}
b[pos] = '#';
if (x > 0 && a[pos + 1] > 0)
{
if (dfs(ksm(x, x, a[pos + 1]), pos + 1) == 1)
{
return 1;
}
}
return 0;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while (1)
{
++cnt;
cin >> a[cnt];
cin >> ch;
if (ch == '=')
{
break;
}
}
cin >> ans;
if (dfs(a[1], 1) == 0)
{
cout << -1 << '\n';
}
return 0;
}