#include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
#include <climits>
using namespace std;
string s[2];
int ans;
int ansx;
vector<int> a;
vector<int> b;
void dfs(int l0, int r0, int l1, int r1, int y) {
if(l0 == r0 && ans > y + a[l0]){
ansx = a[l0];
ans = y + a[l0];
}
if(l0 >= r0) return;
int x = b[r1];
y += x;
int flag = 0;
for (int i = l0; i <= r0; i++) {
if (a[i] == x) {
int cnt = i - l0;
dfs(i + 1, r0, l1 + cnt, r1 - 1, y);
dfs(l0, i - 1, l1, l1 + cnt - 1, y);
break;
}
}
}
void solve() {
a.clear();
b.clear();
getline(cin, s[1]);
stringstream s0(s[0]);
stringstream s1(s[1]);
int x;
while (s0 >> x) {
a.push_back(x);
}
while (s1 >> x) {
b.push_back(x);
}
int p = b.size() - 1;
ans = INT_MAX;
ansx = INT_MAX;
dfs(0, p, 0, p, 0);
cout << ansx << endl;
}
int main() {
// freopen("input", "r", stdin);
while (getline(cin, s[0])) {
solve();
}
}
UVa 548 Tree
最新推荐文章于 2020-09-30 22:43:43 发布
本文深入探讨了C++中深度优先搜索(DFS)算法的应用,通过具体实例讲解了如何利用DFS解决复杂问题,包括状态空间搜索、路径寻找等。文章详细介绍了DFS的递归实现方式,展示了如何在给定的整数数组中找到最优解。
541

被折叠的 条评论
为什么被折叠?



