# 砝码组合（三进制与深度搜索）

题目内容：

5

9-3-1

19

27-9+1

19

27-9+1

#include <stdio.h>
#include <iostream>
using namespace std;
int weight;
int a[5] = {81, 27, 9, 3, 1};
int b[5];
int sum(){
int s = 0;
for(int i = 0; i < 5; i++){
s = s + b[i] * a[i];
}
return s;
}
int DFS(int i){
if(i == 5){
if(sum() == weight){
int k;
for(k = 0; k < 5; k++){
if(b[k] == 1){
cout << a[k];
break;
}
}
for(int i = k + 1; i < 5; i++){
if(b[i] == 1){
cout << "+" << a[i];
}
if(b[i] == -1){
cout << "-" << a[i];
}
}
return 1;
}

}

else{
for(int j = -1; j <= 1; j++){
b[i] = j;
DFS(i + 1);
}
}

}
int main(){
cin >> weight;
DFS(0);

return 0;
}


#include <stdio.h>
#include <iostream>
using namespace std;

int main(){
int a[5] = {1, 3, 9, 27, 81};
int weight;
int w[5] = {0};
cin >> weight;
//先将输入的数字转化为3进制
int i = 0;
while(weight > 0){
w[i] = weight % 3;
weight = weight / 3;
i++;
}
//for(int j = i - 1; j >= 0; j--)
//	cout << w[j];

//将砝码数减少，化为另外一种形式，更大的砝码减小的
for(int j = 0; j < i; j++){
if(w[j] == 2){ //如果是2，该位变为-1且向前进一位
w[j] = -1;
w[j + 1]++;
}
if(w[j] == 3){
w[j] = 0;
w[j + 1]++;
}
}
//for(int j = 4; j >= 0; j--)
//	cout << w[j];

//输出
bool first = true;
for(int i = 4; i >= 0; i--){
if(w[i] == 1 && first != true){
cout << "+" << a[i];
}
if(w[i] == 1 && first == true){
cout << a[i];
first = false;
}
if(w[i] == -1){
cout << "-" << a[i];
}
}

return 0;
}