从两端往中间合并。。。合并过程中的数必然向数小的一方先合并。。。然后我们就可以这样先预处理出关节点。。。然后再关节点上一维DP即可。。。。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 5005
#define maxm 40005
#define eps 1e-10
#define mod 1000000007
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
typedef long long LL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// headint cost[maxn], num[maxn];
int hash[maxn];
int p[maxn];
int dp[maxn];
int n, cnt;void init(void)
{cnt = 0;memset(dp, -1, sizeof dp);
}
void read(void)
{for(int i = 1; i <= n; i++) scanf("%d", &num[i]);for(int i = 1; i <= n; i++) scanf("%d", &cost[i]);
}
int dfs(int now)
{if(~dp[now]) return dp[now];int x = p[now], y = hash[x];if(y - x - 1 > 0) dp[now] = cost[y - x - 1];else dp[now] = 0;for(int i = now+1; i <= cnt; i++) {int xx = p[i], yy = hash[xx];dp[now] = min(dp[now], dfs(i) + cost[xx - x] + cost[y - yy]);}return dp[now];
}
void work(void)
{int i = 0, j = n+1;p[++cnt] = 0, hash[0] = n+1;LL a = 0, b = 0;while(i < j) {if(a <= b) a += num[++i];else b += num[--j];if(a == b) hash[i] = j, p[++cnt] = i;}if(p[cnt] == hash[p[cnt]]) --cnt;printf("%d\n", dfs(1));
}
int main(void)
{while(scanf("%d", &n), n != 0) {init();read();work();}return 0;
}