#include <iostream> 
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <list>
#include <cstring>
#include <map>
#include <set>
#define  ll long long
#define mod 1000000007
#define pi 3.141592653589
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
using namespace std;

int main(){
  int n;
  cin>>n;
  vector<int> v(n);
  for(int i{};i<n;i++)
    cin>>v.at(i);
  vector<int> par(200001,-1);
  vector<int> count(200001,0);
  for(int i{};i<n;i++){
    if(v.at(i)==v.at(n-1-i))
      continue;
    else{
      int f=v.at(i);
      int l=v.at(n-1-i);
      if(par[f]==-1&&par[l]==-1){
        par[f]=f;
        par[l]=f;
      }
      else if(par[f]!=-1&&par[l]==-1)
        par[l]=par[f];
      else if(par[f]==-1&&par[l]!=-1)
        par[f]=par[l];
      else{
        int j{f},k{l};
        while(par[j]!=j){
          par[j]=par[par[j]];
          j=par[j];
        }
        while(par[k]!=k){
          par[k]=par[par[k]];
          k=par[k];
      }
        par[k]=par[j];
      }
    }
  }
    for(int i{};i<200001;i++){
      if(par.at(i)==-1)
        continue;
      else{
        int j=i;
        while(par[j]!=j){
          par[j]=par[par[j]];
          j=par[j];
        }
        count.at(j)++;
      }
    }
    int ans{};
    for(int i{};i<200001;i++){
      if(count.at(i)==0)
        continue;
      ans+=count.at(i)-1;
    }
  cout<<ans<<endl;
}
#include <stdio.h>
#include <map>

int x[100010],y[100010];
int type[100010];
std::map<int,int> check;

int main()
{
	int a,b;
	scanf("%d%d",&a,&b);
	for(int i=1;i<=a;i++) scanf("%d",&x[i]);
	for(int i=1;i<=a;i++) scanf("%d",&y[i]);
	x[0] = 0, y[0] = 0;
	x[a+1] = b+1, y[a+1] = b+1;
	for(int i=1;i<=a;i++)
	{
		if(x[i]>y[i]) type[i] = 1; // <<
		if(x[i]==y[i]) type[i] = 2; // --
		if(x[i]<y[i]) type[i] = 3; // >>
	}
	for(int i=1;i<a;i++)
	{
		if(type[i]==3&&type[i+1]==1)
		{
			printf("-1");
			return 0;
		}
	}
	// x[j] +(i-j) == y[i]
	long long int ans = 0;
	check[0] = 0;
	for(int i=1;i<=a;i++)
	{
		if(type[i]==1)
		{
			if(check.find(y[i]-i)==check.end())
			{
				printf("-1");
				return 0;
			}
			if(y[i-1]==y[i]-1) ans++;
			else
			{
				int k = check[y[i]-i];
				ans += (i-k);
			}
			check[x[i]-i] = i;
		}
		else if(type[i]==2)
		{
			check.clear();
			check[x[i]-i] = i;
		}
	}
	check.clear();
	
	//x[j] - (j-i) == y[i]
	check[(b+1)-(a+1)] = a+1;
	for(int i=a;i>=1;i--)
	{
		if(type[i]==3)
		{
			if(check.find(y[i]-i)==check.end())
			{
				printf("-1");
				return 0;
			}
			if(y[i+1]==y[i]+1) ans++;
			else
			{
				int k = check[y[i]-i];
				ans += (k-i);
			}
			check[x[i]-i] = i;
		}
		else if(type[i]==2)
		{
			check.clear();
			check[x[i]-i] = i;
		}
	}
	printf("%lld",ans);
}