天天看点

UVa 1374 - Power Calculus (DFSID)

题意

问凑成 xn 最少需要几次

思路

好像前面也有一道类似的。用DFSID就行。也可以打表交

代码

  1. #include <cstdio>
  2. #include <stack>
  3. #include <set>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <queue>
  8. #include <functional>
  9. #include <cstring>
  10. #include <algorithm>
  11. #include <cctype>
  12. #include <string>
  13. #include <map>
  14. #include <iomanip>
  15. #include <cmath>
  16. #define LL long long
  17. #define ULL unsigned long long
  18. #define SZ(x) (int)x.size()
  19. #define Lowbit(x) ((x) & (-x))
  20. #define MP(a, b) make_pair(a, b)
  21. #define MS(arr, num) memset(arr, num, sizeof(arr))
  22. #define PB push_back
  23. #define F first
  24. #define S second
  25. #define ROP freopen("input.txt", "r", stdin);
  26. #define MID(a, b) (a + ((b - a) >> 1))
  27. #define LC rt << 1, l, mid
  28. #define RC rt << 1|1, mid + 1, r
  29. #define LRT rt << 1
  30. #define RRT rt << 1|1
  31. #define BitCount(x) __builtin_popcount(x)
  32. #define BitCountll(x) __builtin_popcountll(x)
  33. #define LeftPos(x) 32 - __builtin_clz(x) - 1
  34. #define LeftPosll(x) 64 - __builtin_clzll(x) - 1
  35. const double PI = acos(-1.0);
  36. const int INF = 0x3f3f3f3f;
  37. using namespace std;
  38. const double eps = 1e-6;
  39. const int MAXN = 1100 + 10;
  40. const int MOD = 1000007;
  41. typedef pair<int, int> pii;
  42. typedef vector<int>::iterator viti;
  43. typedef vector<pii>::iterator vitii;
  44. int n, arr[MAXN], depth;
  45. bool DFSID(int curDep)
  46. {
  47. int pre = arr[curDep - 1];
  48. if (curDep == depth)
  49. {
  50. if (pre == n) return true;
  51. return false;
  52. }
  53. if (pre << (depth - curDep) < n) return false;
  54. for (int i = 0; i < curDep; i++)
  55. {
  56. arr[curDep] = pre + arr[i];
  57. if (arr[curDep] <= 1000 && DFSID(curDep + 1)) return true;
  58. arr[curDep] = pre - arr[i];
  59. if (arr[curDep] > 0 && DFSID(curDep + 1)) return true;
  60. }
  61. return false;
  62. }
  63. int main()
  64. {
  65. // ROP;
  66. int i, j;
  67. while (scanf("%d", &n), n)
  68. {
  69. arr[0] = 1;
  70. depth = 1;
  71. while (!DFSID(1)) depth++;
  72. printf("%d\n", depth - 1);
  73. }
  74. return 0;
  75. }