问题
伪代码(排列树)
分析:使用搜索回溯的方法
实现代码
void swapByPermutationTree(int *bot1, int *bot2, int swIdx1, int swIdx2) {//如果swIdx1和swIdx2指向同一个索引则交换函数失效
if (swIdx1 == swIdx2) { return; }
bot1[swIdx1] ^= bot1[swIdx2];
bot1[swIdx2] ^= bot1[swIdx1];
bot1[swIdx1] ^= bot1[swIdx2];
bot2[swIdx1] ^= bot2[swIdx2];
bot2[swIdx2] ^= bot2[swIdx1];
bot2[swIdx1] ^= bot2[swIdx2];
return;
}
int permutationRet = 0x7FFFFFFF;
void permutationTree(int *bot1, int *bot2, int size, int dep, int botT1, int botT2, int now) {
if (dep == size) {
permutationRet = c_min(now, permutationRet);
return;
}
if (now >= permutationRet) { return; }//剪枝
int tep1 = botT1, tep2 = botT2;
for (int i = dep; i < size; ++i) {
/**************************************记录状态并且调用子问题**************************************/
swapByPermutationTree(bot1, bot2, i, dep);
botT1 += bot1[dep];
botT2 = c_max(botT1, botT2) + bot2[dep];
permutationTree(bot1, bot2, size, dep + 1, botT1, botT2, now + botT2);
/**************************************回溯**************************************/
swapByPermutationTree(bot1, bot2, i, dep);
botT1 = tep1;
botT2 = tep2;
}
return;
}
int main() {
int n, bot1[50], bot2[50], state[50];
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> bot1[i];
cin >> bot2[i];
}
permutationTree(bot1, bot2, n, 0, 0, 0, 0);
cout << permutationRet;
}