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
| #include<iostream> #include<cstring> #include<string> #include<cstdio> #include<algorithm> #include<map>
const int N = 100;
using namespace std;
int ans = 0x3f3f3f3f; int n; int a[6] = {1,3,9,27,81}; int bb[6], cc[6]; char b[6], c[6];
void dfs(int sum, int cnt, int pos) { if (cnt >= ans)return; if (pos < -1)return;
if (sum == n) { for (int i = 0; i < 5; i++) { cc[i] = bb[i]; c[i] = b[i]; } ans = cnt; return ; }
dfs(sum, cnt, pos - 1);
bb[pos] = a[pos]; b[pos] = '+'; dfs(sum + a[pos], cnt + 1, pos - 1); bb[pos] = 0; b[pos] = ' ';
bb[pos] = a[pos]; b[pos] = '-'; dfs(sum - a[pos], cnt + 1, pos - 1); bb[pos] = 0; b[pos] = ' '; }
int main() { cin >> n;
dfs(0, 0, 4);
int m = 0;
for (int i = 4; i >= 0; i--) { if (cc[i]) { if (m)cout << c[i]; cout << cc[i]; m++; } } return 0; }
|