标签:
dfs,模拟即可。不难
/*
ID: awsd1231
PROG: zerosum
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int n;
char ch[] = {‘+‘, ‘-‘, ‘ ‘};
void dfs(int x, int change, int befVal, string tmpS) {
char tc = x + ‘0‘;
switch (change) {
case 0 : tmpS += "+"; tmpS += tc; befVal += x; break;
case 1 : tmpS += "-"; tmpS += tc; befVal -= x; break;
case 2 : char tmp = ‘+‘; int tmpVal = 0;
for (int i = 0; i != tmpS.length(); ++i) {
if (tmpS[i] != ‘ ‘ && (tmpS[i] < ‘1‘ || tmpS[i] > ‘9‘)) {
tmp = tmpS[i];
tmpVal = 0;
}
else if (tmpS[i] != ‘ ‘) {
tmpVal = tmpVal * 10 + tmpS[i] - ‘0‘;
}
}
switch (tmp) {
case ‘+‘ : befVal += tmpVal * 9 + x; break;
case ‘-‘ : befVal -= tmpVal * 9 + x; break;
}
tmpS += " "; tmpS += tc; break;
}
if(x == n) {
if (befVal == 0)
cout << tmpS << endl;
return;
}
dfs(x + 1, 2, befVal, tmpS);
dfs(x + 1, 0, befVal, tmpS);
dfs(x + 1, 1, befVal, tmpS);
}
int main () {
freopen("zerosum.in", "r", stdin);
freopen("zerosum.out", "w", stdout);
scanf("%d", &n);
string ans("1");
dfs(2, 2, 1, ans);
dfs(2, 0, 1, ans);
dfs(2, 1, 1, ans);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/liangyongrui/p/4558454.html