UVa 548 Tree

include

include

include

include

include

using namespace std;
string s[2];
int ans;
int ansx;
vector a;
vector 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)