n,m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) u = [0]*(n+1); d = [0]*(n+1); k = 100 for i,(x,y) in enumerate(zip(a,b),1): u[i] = (y-x)%m; d[i] = (x-y)%m dpu = [list(range(0,m*k,m))]+[[0]*k for i in range(n)] dpd = [list(range(0,m*k,m))]+[[0]*k for i in range(n)] for i in range(n): dpu[i+1][0] = min(dpu[i][0]+max(u[i+1]-u[i],0),dpd[i][0]+u[i+1]) dpd[i+1][0] = min(dpd[i][0]+max(d[i+1]-d[i],0),dpu[i][0]+d[i+1]) for j in range(1,k): dpu[i+1][j] = min(dpu[i][j]+max(u[i+1]-u[i],0),dpu[i][j-1]+u[i+1]+m-u[i]) dpd[i+1][j] = min(dpd[i][j]+max(d[i+1]-d[i],0),dpd[i][j-1]+d[i+1]+m-d[i]) for j in range(k-1): dpu[i+1][j] = min(dpu[i+1][j],dpu[i][j+1]) dpd[i+1][j] = min(dpd[i+1][j],dpd[i][j+1]) print(min(*dpu[n],*dpd[n]))