题目大意:给出5个整数和4种运算(加法,减法,乘法和除法),选取其中的部分数作任意运算,使得值等于目标数或者最接近目标数。其中,除法只能整除,即商必须是整数。
解题思路:每次选取任意两个数,进行可行的运算,获得结果并且和目标数作比较。最后得出答案。
代码如下:
1 #include <iostream> 2 //#include <ctime> 3 #include <vector> 4 #include <climits> 5 using namespace std; 6 7 const int maxn = 5; 8 int target; 9 int approximation; 10 int n; 11 12 bool test(const int &res) { 13 bool flag = false;; 14 if (res == target) { 15 approximation = res; 16 flag = true; 17 } else if (res < target) { 18 approximation = approximation > res ? approximation : res; 19 } 20 return flag; 21 } 22 23 int add(const int & a, const int & b) { 24 return a + b; 25 } 26 27 int sub(const int & a, const int & b) { 28 return a - b; 29 } 30 31 int mul(const int & a, const int & b) { 32 return a * b; 33 } 34 35 int div(const int & a, const int & b, bool &flag) { 36 int res = 0; 37 38 if (a < b) { 39 if (a != 0 && b % a == 0) { 40 res = b / a; 41 flag = true; 42 } else { 43 flag = false; 44 } 45 } else { 46 if (b != 0 && a % b == 0) { 47 res = a / b; 48 flag = true; 49 } else { 50 flag = false; 51 } 52 } 53 54 return res; 55 } 56 57 void deal(const vector<int> & nums) { 58 if (approximation == target) return; 59 if (nums.size() < 2) return; 60 61 for (int i = 0; i < nums.size(); i++) { 62 for (int j = i + 1; j < nums.size(); j++) { 63 vector<int> nnums; 64 nnums.insert(nnums.end(), nums.begin(), nums.begin() + i); 65 nnums.insert(nnums.end(), nums.begin() + i + 1, nums.begin() + j); 66 nnums.insert(nnums.end(), nums.begin() + j + 1, nums.end()); 67 68 int res; 69 res = add(nums[i], nums[j]); 70 if (test(res)) return; 71 nnums.push_back(res); 72 deal(nnums); 73 74 nnums.pop_back(); 75 76 res = sub(nums[i], nums[j]); 77 if (test(res)) return; 78 nnums.push_back(res); 79 deal(nnums); 80 81 nnums.pop_back(); 82 83 res = sub(nums[j], nums[i]); 84 if (test(res)) return; 85 nnums.push_back(res); 86 deal(nnums); 87 88 nnums.pop_back(); 89 90 res = mul(nums[i], nums[j]); 91 if (test(res)) return; 92 nnums.push_back(res); 93 deal(nnums); 94 95 nnums.pop_back(); 96 97 bool flag; 98 res = div(nums[i], nums[j], flag); 99 if (flag == false) continue; 100 if (test(res)) return; 101 nnums.push_back(res); 102 deal(nnums); 103 104 nnums.pop_back(); 105 106 107 } 108 } 109 } 110 111 int main() { 112 cin >> n; 113 while (n--) { 114 vector<int> nums; 115 int temp; 116 for (int i = 0; i < maxn; i++) { 117 cin >> temp; 118 nums.push_back(temp); 119 } 120 cin >> target; 121 approximation = -INT_MAX; 122 123 //double start = clock(); 124 deal(nums); 125 //double end = clock(); 126 //cout << (end - start) / CLOCKS_PER_SEC << endl; 127 128 cout << approximation << endl; 129 130 } 131 return 0; 132 }