Files
python/TangDou/CSP-J/J1_2020/dfs.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

51 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
int n;
int d[50][2];
int ans;
void dfs(int n, int sum) {
if (n == 1) { //递归出口,最后一行时就停止了
ans = max(sum, ans); // max(每条路径的最结果)
return;
}
//当站在第n个位置时,有下面n-1 种选择
//枚举所有比自己小的行
for (int i = 1; i < n; i++) {
//相邻行叠加
int a = d[i - 1][0];
int b = d[i - 1][1];
int x = d[i][0];
int y = d[i][1];
d[i - 1][0] = a + x; //叠加
d[i - 1][1] = b + y; //叠加
for (int j = i; j < n; j++)
d[j][0] = d[j + 1][0], d[j][1] = d[j + 1][1]; //空行用复制数据过来n-1-i行
int s = a + x + abs(b - y); //第一列和+abs(第二列差)
//走下一个位置
dfs(n - 1, sum + s);
//还原现场
for (int j = n - 1; j > i; j--)
d[j][0] = d[j - 1][0], d[j][1] = d[j - 1][1];
d[i - 1][0] = a;
d[i - 1][1] = b;
d[i][0] = x;
d[i][1] == y;
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> d[i][0]; // n行第0列
for (int i = 0; i < n; i++) cin >> d[i][1]; // n行第1列
dfs(n, 0);
cout << ans << endl;
return 0;
}