日期:2026年11月25日
ZeroJudge 題目連結:n132.p4. 隊伍分配
解題想法
這題要用 dfs 窮舉所有可能的隊伍分配方式,並用集合 $tested$ 記錄已經測試過的小隊戰力加總,避免重複跑相同的值。詳細的過作過程請看程式碼中的註解。
Python 程式碼
使用時間約為 2.9 s,記憶體約為 9.8 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
n = int(data[ptr]) # 人數 n
k = int(data[ptr + 1]) # 小隊數量 k
ptr += 2
m = n // k # 每組人數 m
arr = tuple(map(int, data[ptr : ptr + n])) # 讀取每人的戰力
ptr += n
imax = 0 # 團隊戰力最大值,預設為 0
def dfs(teams, idx): # 自訂函式,遞迴窮舉求解
nonlocal imax # 全域變數
# 遞迴出口,分配完成,計算整體戰力
if idx == n:
total = 1 # 團隊戰力預設為 1
# 依序由 teams 讀取小隊每人戰力,用 sum 加總,與 total 相乘
for team in teams:
total *= sum(team)
# 更新 imax
imax = max(imax, total)
return # 離開函式
# 回溯及遞迴的部分
tested = set() # 已測試過的小隊戰力加總
for i in range(k): # 依序檢測 k 個小隊
if len(teams[i]) < m: # 如果該小隊未填滿
isum = sum(teams[i]) # 計算小隊戰力加總 isum
if isum in tested: continue # 如果 isum 已測試過,跑下一個值
tested.add(isum) # 將 isum 加入 tested
teams[i].append(arr[idx]) # 將士兵加入該小隊
dfs(teams, idx + 1) # 遞迴,代入 teams 及 idx + 1
teams[i].pop() # 回溯
# 呼叫 dfs,代入長度 k 的二維空串列求解
dfs([[] for _ in range(k)], 0)
result.append(f"{imax:d}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 0.5 s,記憶體約為 3.8 MB,通過測試。
#include <iostream>
#include <vector>
#include <unordered_set>
#include <numeric>
#include <algorithm>
typedef long long LL;
using namespace std;
int n, k, m; // 人數 n,小隊數量 k,每組人數 m
vector<int> arr; // 每人的戰力
vector<vector<int>> teams; // 小隊分配
LL imax; // 團隊戰力最大值
void solve(int idx) { // 自訂函式,遞迴窮舉求解
if (idx == n) { // 遞迴出口,分配完成,計算整體戰力
LL total = 1; // 團隊戰力預設為 1
for(auto team : teams) { // 依序由 teams 讀取小隊每人戰力
LL isum = accumulate(team.begin(), team.end(), 0LL); // 計算小隊戰力加總 isum 加總
total *= isum; // 與 total 相乘
}
imax = max(imax, total); // 更新 imax
return; // 離開函式
}
/* 回溯及遞迴的部分 */
unordered_set<LL> tested; // 已測試過的小隊戰力加總
for(int i = 0; i < k; i++) { // 依序檢測 k 個小隊
if ((int)teams[i].size() < m) { // 如果該小隊未填滿
LL isum = accumulate(teams[i].begin(), teams[i].end(), 0LL); // 計算小隊戰力加總 isum 加總
if (tested.count(isum) == 1) continue; // 如果 isum 已測試過,跑下一個值
tested.insert(isum); // 將 isum 加入 tested
teams[i].push_back(arr[idx]); // 將士兵加入該小隊
solve(idx + 1); // 遞迴,代入 idx+1
teams[i].pop_back(); // 回溯
}
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); // 加速
while(cin >> n >> k) { // 讀取 n、k
m = n / k; // 計算 m
arr.assign(n, 0); // 重設 arr
for(int i = 0; i < n; i++) { // 讀取每人戰力
cin >> arr[i];
}
//teams.assign(k, vector<int> (0)); // 重設 teams
teams.resize(k); // 重設 teams
imax = 0;
solve(0); // 呼叫 solve 求解
cout << imax << "\n"; // 印出 imax
}
return 0;
}
沒有留言:
張貼留言