机试题——最大发射功率

题目描述

某设备工作时有两个通道(A和B)向外发射信号,每个通道的发射功率由License控制。License可以叠加使用,但不能拆分。用户希望两个通道能够以最大且相同的功率发射信号。

输入描述

  1. 第一行:一个整数num,表示用户现有的License数量(0 <= num <= 50)。
  2. 第二行:num个整数的数组,表示每个License的功率大小(0 <= 功率 <= 50)。

输出描述

一个整数,表示每个通道的最大可能发射功率。如果无法分配,则通道发射功率为0

用例输入

5
2 4 6 8 10
14

可以选择6 + 8 = 144 + 10 = 14,每个通道的最大发射功率为14

3
1 2 4
0

无法将现有License分配到两个通道,使两个通道的功率相同。

解题思路

  1. 问题建模

    • 该问题可以看作是一个划分等和子集问题,目标是将所有License的功率划分为两个和相等的子集。(可以有的元素不分,不能直接DP求sum/2的是否存在)
  2. 深度优先搜索(DFS)

    • 使用DFS遍历所有可能的分配方案,尝试将每个License分配到两个通道中的一个,或者不分。
    • 使用剪枝优化DFS:
      • 如果当前通道的功率已经超过总功率的一半,则直接返回。
      • 从大到小排序License,尽快触发剪枝条件。

DFS代码(50%)

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int res = 0;
int check = 0;
void dfs(const vector<int>& nums, int index, int target1, int target2) {
    if (target1 > check / 2) return;
    if (index == nums.size()) {
        if (target1 == target2) {
            res = max(target1, res);
        }
        return;
    }
    dfs(nums, index + 1, target1, target2);
    dfs(nums, index + 1, target1+ nums[index], target2);
    dfs(nums, index + 1, target1 , target2+ nums[index]);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, t;
    cin >> n;
    vector<int> nums;
    for (int i = 0; i < n; i++) {
        cin >> t;
        if (t == 0) continue;
        else {
            nums.push_back(t);
            check += t;
        }
    }
    //排序 从大的开始 尽快触发剪枝条件
    sort(nums.rbegin(), nums.rend());
    dfs(nums, 0, 0, 0);
    cout << res;
}

DP (100%)

你可能感兴趣的:(#,hw机试题,深度优先,算法)