Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.

There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.

You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.

Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.


-----Input-----

The first line of input contains three integers n, m and k (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 10^5, 1 ≤ k ≤ 10^6). 

The i-th of the following m lines contains the description of the i-th flight defined by four integers d_{i}, f_{i}, t_{i} and c_{i} (1 ≤ d_{i} ≤ 10^6, 0 ≤ f_{i} ≤ n, 0 ≤ t_{i} ≤ n, 1 ≤ c_{i} ≤ 10^6, exactly one of f_{i} and t_{i} equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.


-----Output-----

Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.

If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).


-----Examples-----
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500

Output
24500

Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000

Output
-1



-----Note-----

The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.

In the second sample it is impossible to send jury member from city 2 back home from Metropolis.

Difficulty: competition

Starter code:

Solutions:
N,M,K = map(int,input().split())

INF = 10**6+1
from collections import defaultdict

incoming = defaultdict(list)
outgoing = defaultdict(list)

for _ in range(M):
  d,f,t,c = map(int,input().split())
  if t == 0:
    incoming[d].append((c,f-1))
  if f == 0:
    outgoing[d].append((c,t-1))

incoming_dates = sorted(incoming.keys())
outgoing_dates = sorted(outgoing.keys(),reverse=True)



Li = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0

for d in incoming_dates:
  for c,x in incoming[d]:
    if mark[x]:
      if costs[x] > c:
        total_cost += c-costs[x]
        costs[x] = c
    else:
      mark[x] = True
      cnt += 1
      costs[x] = c
      total_cost += c

  if cnt == N:
    Li.append((d,total_cost))


Lo = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0

for d in outgoing_dates:
  for c,x in outgoing[d]:
    if mark[x]:
      if costs[x] > c:
        total_cost += c-costs[x]
        costs[x] = c
    else:
      mark[x] = True
      cnt += 1
      costs[x] = c
      total_cost += c

  if cnt == N:
    Lo.append((d,total_cost))

Lo.reverse()


if not Li or not Lo:
  print(-1)
  return


# print(Li,Lo)

from bisect import bisect

best = float('inf')

for d,c in Li:
  i = bisect(Lo,(d+K+1,0))
  if i >= len(Lo):
    break
  else:
    best = min(best,c+Lo[i][1])

if best == float('inf'):
  print(-1)
else:
  print(best)

def main():
    n, m, k = list(map(int, input().split()))
    ff, tt = [], []
    for _ in range(m):
        d, f, t, c = list(map(int, input().split()))
        if f:
            ff.append((d, f, c))
        else:
            tt.append((-d, t, c))
    for ft in ff, tt:
        cnt, costs = n, [1000001] * (n + 1)
        ft.sort(reverse=True)
        while ft:
            day, city, cost = ft.pop()
            oldcost = costs[city]
            if oldcost > cost:
                costs[city] = cost
                if oldcost == 1000001:
                    cnt -= 1
                    if not cnt:
                        break
        else:
            print(-1)
            return
        total = sum(costs) - 1000001
        l = [(day, total)]
        while ft:
            day, city, cost = ft.pop()
            oldcost = costs[city]
            if oldcost > cost:
                total -= oldcost - cost
                costs[city] = cost
                if l[-1][0] == day:
                    l[-1] = (day, total)
                else:
                    l.append((day, total))
        if ft is ff:
            ff = l
        else:
            tt = l
    l, k = [], -k
    d, c = tt.pop()
    try:
        for day, cost in ff:
            while d + day >= k:
                d, c = tt.pop()
            if d + day < k:
                l.append(c + cost)
    except IndexError:
        pass
    print(min(l, default=-1))


def __starting_point():
    main()

__starting_point()

g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(3e11)

for i in range(m):
    d, f, t, c = g()
    if f: F.append((d, f, c))
    else: T.append((-d, t, c))

for p in [F, T]:
    C = [e] * (n + 1)
    s = n * e
    q = []

    p.sort()
    for d, t, c in p:
        if C[t] > c:
            s += c - C[t]
            C[t] = c
            if s < e: q.append((s, d))
    p.clear()
    p += q

s, t = e, (0, 0)
for f in F:
    while f:
        if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
        elif T:
            t = T.pop()
            continue
        f = 0

print(s if s < e else -1)

R=lambda :list(map(int,input().split()))
n,m,k=R()
F,T=[],[]
ans=int(1e12)
for i in range(m):
    d,f,t,c=R()
    if f:F.append((d,f,c))
    else:T.append((-d,t,c))
for p in [F,T]:
    cost=[ans]*(n+1)
    s=n*ans
    q=[]
    p.sort()
    for d,t,c in p:
        #print(p)
        if c<cost[t]:
            #print(c,cost[t])
            s+=c-cost[t]
            #print(s)
            cost[t]=c
            if s<ans:
                q.append((s,d))
    p.clear()
    #print(q)
    p+=q
    #print(p)
s,t=ans,(0,0)
#print(F,T)
for f in F:
    while  f:
        if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])
        elif T:
            #print(T)
            t=T.pop()
            #print(T)
           # print(t)
            continue
        #print(f)
        f=0
        #print(f)
print(s if s<ans else -1)


R=lambda :list(map(int,input().split()))

n,m,k=R()

F,T=[],[]

ans=int(1e12)

for i in range(m):

    d,f,t,c=R()

    if f:F.append((d,f,c))

    else:T.append((-d,t,c))

for p in [F,T]:

    cost=[ans]*(n+1)

    s=n*ans

    q=[]

    p.sort()

    for d,t,c in p:

        #print(p)

        if c<cost[t]:

            #print(c,cost[t])

            s+=c-cost[t]

            #print(s)

            cost[t]=c

            if s<ans:

                q.append((s,d))

    p.clear()

    #print(q)

    p+=q

    #print(p)

s,t=ans,(0,0)

#print(F,T)

for f in F:

    while  f:

        if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])

        elif T:

            #print(T)

            t=T.pop()

            #print(T)

           # print(t)

            continue

        #print(f)

        f=0

        #print(f)

print(s if s<ans else -1)





# Made By Mostafa_Khaled


g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(3e11)

for i in range(m):
    d, f, t, c = g()
    if f: F.append((d, f, c))
    else: T.append((-d, t, c))

for p in [F, T]:
    C = [e] * (n + 1)
    s = n * e
    q = []

    p.sort()
    for d, t, c in p:
        if C[t] > c:
            s += c - C[t]
            C[t] = c
            if s < e: q.append((s, d))
    p.clear()
    p += q

s, t = e, (0, 0)
for f in F:
    while f:
        if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
        elif T:
            t = T.pop()
            continue
        f = 0

print(s if s < e else -1)

from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
    print(-1)
    return
for i in range(m):
    pln.append([int(i) for i in input().split()])
pln.sort()

grp=[[pln[0]]];gt=0;
for i in range(1,m):
    if pln[i][0]!=pln[i-1][0]:
        gt=gt+1
        grp.append([])
    grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
    xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)

from math import inf
pre=[0]*len(xx)
ct=0 
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if ti==0:
            if mincost[fi]==inf:
                ct+=1
            if sumcost==inf:
                mincost[fi]=min(mincost[fi],ci)
            else:
                sumcost=sumcost-mincost[fi]
                mincost[fi]=min(mincost[fi],ci)
                sumcost=sumcost+mincost[fi]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    pre[i]=sumcost
#print(pre)

sa=[0]*len(xx)
ct=0 
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if fi==0:
            if mincost[ti]==inf:
                ct+=1
            if sumcost==inf:
                mincost[ti]=min(mincost[ti],ci)
            else:
                sumcost=sumcost-mincost[ti]
                mincost[ti]=min(mincost[ti],ci)
                sumcost=sumcost+mincost[ti]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    sa[i]=sumcost
sa.reverse()
#print(sa)

ans=inf
for l,xxi in enumerate(xx):
    r=bisect_right(xx,xxi+k)
    ansl=pre[l]
    ansr= inf if r==len(xx) else sa[r]
    ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)