// https://loj.ac/s/2069475
// 提交时间 2024/05/23 15:24:18
// Problem: #2509. 「AHOI / HNOI2018」排列
// Contest: LibreOJ
// URL: https://loj.ac/p/2509
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// Author: nullptr_qwq
//
// Powered by CP Editor (https://cpeditor.org)
// 私は猫です
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define ll long long
#define pb push_back
#define mkp make_pair
#define fi first
#define se second
#define inf 1e9
#define infll 1e18
#define pii pair<int,int>
#define F(i,a,b) for(int i=a;i<=(b);i++)
#define dF(i,a,b) for(int i=a;i>=(b);i--)
#define wh(lzm) while(lzm--)
#define cmh(sjy) while(sjy--)
#define lowbit(x) (x&(-x))
#define HH printf("\n")
#define eb emplace_back
using namespace std;
ll read(){
ll x=0,f=1; char c=getchar();
while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
return x*f;
}
const int mod=998244353,maxn=500005;
vector<int>g[maxn];
int n,a[maxn],fa[maxn],sz[maxn];
ll w[maxn];
int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]); }
struct node{
int u,siz;
ll sum;
bool operator<(const node &rhs)const{ return 1ll*sum*rhs.siz>1ll*rhs.sum*siz; }
};
priority_queue<node>q;
void solve(){
n=read();
F(i,1,n) fa[i]=i;
F(i,1,n) g[a[i]=read()].push_back(i);
F(i,1,n) {
int x=find(a[i]),y=find(i);
if(x==y) return puts("-1"),void();
fa[x]=y;
}
F(i,0,n) fa[i]=i,sz[i]=1;
F(i,1,n) w[i]=read();
F(i,1,n) q.push((node){i,1,w[i]});
ll ans=0;
while(!q.empty()){
auto [u,siz,S]=q.top(); q.pop();
if(sz[u=find(u)]!=siz) continue;
int p=find(a[u]);
ans+=1ll*w[u]*sz[p];
sz[p]+=sz[u],w[p]+=w[u],fa[u]=p;
if(p>0) q.push({p,sz[p],w[p]});
}
cout<<ans;
}
signed main(){
int sjy=1;
cmh(sjy) solve();
}