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 = 200 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)); dpd = list(range(0,m*k,m)) for i in range(n): equ = [0]*k; eqd = [0]*k equ[0] = min(dpu[0]+max(u[i+1]-u[i],0),dpd[0]+u[i+1]) eqd[0] = min(dpd[0]+max(d[i+1]-d[i],0),dpu[0]+d[i+1]) for j in range(1,k): equ[j] = min(dpu[j]+max(u[i+1]-u[i],0),dpu[j-1]+u[i+1]+m-u[i]) eqd[j] = min(dpd[j]+max(d[i+1]-d[i],0),dpd[j-1]+d[i+1]+m-d[i]) for j in range(k-1): equ[j] = min(equ[j],dpu[j+1]) eqd[j] = min(eqd[j],dpd[j+1]) dpu,dpd = equ,eqd print(min(*dpu,*dpd))