#include <bits/stdc++.h>
using namespace std;

int a[100010], b[100010];
map <int, vector <int> > all;
map <int, int> cnt, sum;

int main () {
	int n, L; scanf("%d%d", &n, &L);
	a[0] = 0, a[n + 1] = L + 1;
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	for (int i = 0; i <= n + 1; i++) {
		all[a[i] - i].push_back(i);
	}
	long long ans = 0;
	for (int i = 1; i <= n; i++) {
		scanf("%d", &b[i]);
		b[i] -= i;
		if (!all.count(b[i])) {
			printf("-1\n");
			return 0;
		}
		vector <int> &tmp = all[b[i]];
		int pos = lower_bound(tmp.begin(), tmp.end(), i) - tmp.begin();
		int p = 0x3f3f3f3f;
		if (pos != tmp.size()) {
			if (abs(p - i) > abs(tmp[pos] - i)) p = tmp[pos];
		}
		if (pos) {
			pos--;
			if (abs(p - i) > abs(tmp[pos] - i)) p = tmp[pos];
		}
		if (p > i) cnt[b[i] * 2]++, sum[b[i] * 2] = max(sum[b[i] * 2], abs(p - i));
		else if (p < i) cnt[b[i] * 2 + 1]++, sum[b[i] * 2 + 1] = max(sum[b[i] * 2 + 1], abs(p - i));
	}
	for (map <int, int> :: iterator it = cnt.begin(); it != cnt.end(); it++) {
		int x = it->first;
		ans += sum[x];
	}
	printf("%lld\n", ans);
	return 0;
}

/*
 * @Author: zhl
 * @LastEditTime: 2021-02-13 22:14:39
 */
#include<bits/stdc++.h>
using namespace std;

const int N = 2e3 + 10;
typedef long long ll;

char mp[N][N];
int n,m;
vector<int>G[N];
int fa[N];
int find(int a){
    return a == fa[a] ? a : fa[a] = find(fa[a]);
}
void merge(int a,int b){
    a = find(a);b = find(b);
    if(a != b)fa[a] = b;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n;i++)scanf("%s",mp[i] + 1),fa[i] = i;

    merge(1,n);

    for(int j = 1;j <= m;j++){
        for(int i = 1;i <= n;i++){
            if(mp[i][j] == '#')G[j].push_back(i);
        }
        int sz = G[j].size();
        if(G[j].empty())continue;

        for(int ii = 1;ii < sz;ii++){
            merge(G[j][ii], G[j][0]);
        }
        if(j == 1 or j == m)merge(G[j][0],1);
    }
    
    set<int>rt;
    for(int i = 1;i <= n;i++)rt.insert(find(i));

    int ans = rt.size() - 1;

    for(int i = 1;i <= m;i++)fa[i] = i;
    merge(1,m);

    for(int i = 1;i <= n;i++){
        G[i].clear();
        for(int j = 1;j <= m;j++){
            if(mp[i][j] == '#')G[i].push_back(j);
        }
        int sz = G[i].size();
        if(G[i].empty())continue;

        for(int ii = 1;ii < sz;ii++){
            merge(G[i][ii], G[i][0]);
        }
        if(i == 1 or i == n)merge(G[i][0],1);
    }
    rt.clear();
    for(int i = 1;i <= m;i++)rt.insert(find(i));
    cout << min(ans,int(rt.size()) - 1) << endl;
    
}