UVa 548 Tree

#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();
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值