USACO Zero Sum

Code

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
/*
ID: wcr19961
PROG: zerosum
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 10;
const char s[] = " +-";
int a[maxn];

void dfs(int d, int n) {
if (d == n) {
int sum = 0, pre = 1;
for (int i = 1; i < n; ++i) {
if (a[i] == 1) {
sum += pre;
pre = i + 1;
} else if (a[i] == 2) {
sum += pre;
pre = -i - 1;
} else {
pre *= 10;
if (pre > 0) {
pre += i + 1;
} else {
pre -= i + 1;
}
}
}
sum += pre;
if (sum == 0) {
putchar('1');
for (int i = 1; i < n; ++i) {
printf("%c%d", s[a[i]], i + 1);
}
puts("");
}
return;
}
for (int i = 0; i < 3; ++i) {
a[d] = i;
dfs(d + 1, n);
}
}

int main() {
freopen("zerosum.in", "r", stdin);
freopen("zerosum.out", "w", stdout);
int n;
scanf("%d", &n);
dfs(1, n);
return 0;
}