#include<bits/stdc++.h>
using namespace std;
int n,a[202020],b[202020],c[202020];
int tr[202020];
void gx(int x)
{
	while(x<=n)
	{
		tr[x]++;
		x+=(x&(-x));
	}
}
int gt(int x)
{
	int ans=0;
	while(x>0)
	{
		ans+=tr[x];
		x-=(x&(-x));
	}
	return ans;
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		a[i]+=i;
	}
	for(int i=1;i<=n;i++)
	{
		cin>>b[i];
		b[i]+=i;
	}
	vector<pair<int,int> >v1,v2;
	for(int i=1;i<=n;i++)
	{
		v1.push_back(make_pair(a[i],i));
		v2.push_back(make_pair(b[i],i));
	}
	sort(v1.begin(),v1.end());
	sort(v2.begin(),v2.end());
	bool ok=true;
	long long ans=0;
	for(int i=0;i<n;i++)
	{
		if(v1[i].first!=v2[i].first)
		{
			ok=false;
			break;
		}
	}
	if(!ok)
	{
		cout<<-1<<endl;
		return 0;
	}
	for(int i=0;i<n;i++)
	{
		c[v2[i].second]=v1[i].second;
	}
	for(int i=1;i<=n;i++)
	{
//		cout<<c[i]<<endl;
		gx(c[i]);
		ans+=(i-gt(c[i]));
//		cout<<gt(c[i])<<endl;
	}
	cout<<ans<<endl;
	return 0;
}
#include<bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int i=(a),(i##i)=(b);i<=(i##i);++i)
#define rep(i,n) for(int i=0,(i##i)=(n);i<(i##i);++i)
#define Fodn(i,a,b) for(int i=(a),(i##i)=(b);i>=(i##i);--i)
#define pln puts("")
#define il inline
#define pb push_back()
#define ff first
#define ss second
using LL=long long;
using U32=unsigned int;
using U64=unsigned LL;
using LD=long double;
template<typename T>
using pii=pair<T,T>;
template<typename T>
il bool read(T&x){
    x=0;char c=getchar();int f=1;
    while(!isdigit(c)&&(c!='-')&&(c!=EOF))c=getchar();
    if(c==EOF)return 0;if(c=='-')f=-1,c=getchar();
    while(isdigit(c)){x=(x<<1)+(x<<3)+(c&15);c=getchar();}
    x*=f;return 1;
}
template<typename T,typename...Args>
il bool read(T&x,Args&...args){bool res=1;res&=read(x);res&=read(args...);return res;}
const double EPS=1e-6;
const int M=1000000007,INF=0x3f3f3f3f;
const LL INFLL=0x3f3f3f3f3f3f3f3fLL;
const int N=500010;

int fa[N],d[N],s[N];
int f(int x){
    if(fa[x]==x)return x;
    return fa[x]=f(fa[x]);
}
int n,a[N],b[N];
bool h[N];
il void init(){
    read(n);For(i,1,n)read(a[i],b[i]);
    For(i,1,400000)fa[i]=i,s[i]=1;
}
int ans;
il void solve(){
    For(i,1,n){
        int u=f(a[i]),v=f(b[i]);
        if(u==v)++d[u];
        else{
            fa[u]=v;
            d[v]+=d[u]+1;
            s[v]+=s[u];
        }
    }
    For(i,1,400000){
        int u=f(i);
        if(h[u])continue;
        h[u]=1;
        if(d[u]+1==s[u])ans+=d[u];else ans+=s[u];
    }
    printf("%d\n",ans);
}

signed main(){
    init();solve();
    return 0;
}