大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.8 KiB

2 weeks ago
  1. /*
  2. PK!ai代表目己的战斗力使
  3. */
  4. #include <iostream>
  5. #include <vector>
  6. #include <cmath>
  7. #include <numeric>
  8. using namespace std;
  9. int findClosestSum(vector<int>& nums, int target) {
  10. int sum = accumulate(nums.begin(), nums.end(), 0); // 数组元素的总和
  11. int maxSum = min(sum, target + abs(sum - target)); // 限制最大的可能和
  12. vector<bool> dp(maxSum + 1, false); // dp数组,初始为 false
  13. dp[0] = true; // 和为 0 是可能的
  14. // 动态规划填充 dp 数组
  15. for (int num : nums) {
  16. for (int i = maxSum; i >= num; --i) {
  17. dp[i] = dp[i] || dp[i - num];
  18. }
  19. }
  20. // 从 dp 数组中找到最接近目标值的和
  21. int closest = 0;
  22. for (int i = 0; i <= maxSum; ++i) {
  23. if (dp[i] && abs(i - target) < abs(closest - target)) {
  24. closest = i;
  25. }
  26. }
  27. return closest;
  28. }
  29. int main() {
  30. int n;
  31. vector<int> arr;
  32. int val, sum = 0;
  33. cin >> n;
  34. for(int i = 0; i < n; i++){
  35. cin >> val;
  36. sum += val;
  37. arr.push_back(val);
  38. }
  39. int arv = sum / 2;
  40. int tmp = findClosestSum(arr, arv);
  41. cout << tmp << endl;
  42. cout << arv - tmp + sum - tmp - arv << endl;
  43. return 0;
  44. }
  45. #include <iostream>
  46. #include <vector>
  47. #include <cmath>
  48. #include <numeric>
  49. using namespace std;
  50. int findClosestSum(vector<int>& nums, int target) {
  51. int n = nums.size();
  52. int sum = accumulate(nums.begin(), nums.end(), 0); // 数组元素的总和
  53. int maxSum = min(sum, target + abs(sum - target)); // 限制最大的可能和
  54. vector<bool> dp(maxSum + 1, false); // dp数组,初始为 false
  55. dp[0] = true; // 和为 0 是可能的
  56. // 动态规划填充 dp 数组
  57. for (int num : nums) {
  58. for (int i = maxSum; i >= num; --i) {
  59. dp[i] = dp[i] || dp[i - num];
  60. }
  61. }
  62. // 从 dp 数组中找到最接近目标值的和
  63. int closest = 0;
  64. for (int i = 0; i <= maxSum; ++i) {
  65. if (dp[i] && abs(i - target) < abs(closest - target)) {
  66. closest = i;
  67. }
  68. }
  69. return closest;
  70. }
  71. int main() {
  72. vector<int> nums = {7,3,5,3}; // 输入数组
  73. int target = 10; // 目标值
  74. int result = findClosestSum(nums, target);
  75. cout << result << endl;
  76. return 0;
  77. }