2.3.3 Zero Sum

dfs,模拟即可。不难

   
     
  1. /*
  2. ID: awsd1231
  3. PROG: zerosum
  4. LANG: C++
  5. */
  6. #include<iostream>
  7. #include<cstdio>
  8. #include<string>
  9. using namespace std;
  10. int n;
  11. char ch[] = {'+', '-', ' '};
  12. void dfs(int x, int change, int befVal, string tmpS) {
  13. char tc = x + '0';
  14. switch (change) {
  15. case 0 : tmpS += "+"; tmpS += tc; befVal += x; break;
  16. case 1 : tmpS += "-"; tmpS += tc; befVal -= x; break;
  17. case 2 : char tmp = '+'; int tmpVal = 0;
  18. for (int i = 0; i != tmpS.length(); ++i) {
  19. if (tmpS[i] != ' ' && (tmpS[i] < '1' || tmpS[i] > '9')) {
  20. tmp = tmpS[i];
  21. tmpVal = 0;
  22. }
  23. else if (tmpS[i] != ' ') {
  24. tmpVal = tmpVal * 10 + tmpS[i] - '0';
  25. }
  26. }
  27. switch (tmp) {
  28. case '+' : befVal += tmpVal * 9 + x; break;
  29. case '-' : befVal -= tmpVal * 9 + x; break;
  30. }
  31. tmpS += " "; tmpS += tc; break;
  32. }
  33. if(x == n) {
  34. if (befVal == 0)
  35. cout << tmpS << endl;
  36. return;
  37. }
  38. dfs(x + 1, 2, befVal, tmpS);
  39. dfs(x + 1, 0, befVal, tmpS);
  40. dfs(x + 1, 1, befVal, tmpS);
  41. }
  42. int main () {
  43. freopen("zerosum.in", "r", stdin);
  44. freopen("zerosum.out", "w", stdout);
  45. scanf("%d", &n);
  46. string ans("1");
  47. dfs(2, 2, 1, ans);
  48. dfs(2, 0, 1, ans);
  49. dfs(2, 1, 1, ans);
  50. return 0;
  51. }





你可能感兴趣的:(zero)