As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.

Elections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $i$-th voter $c_i$ bytecoins you can ask him to vote for any other party you choose.

The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.


-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \le n, m \le 3000$) — the number of voters and the number of parties respectively.

Each of the following $n$ lines contains two integers $p_i$ and $c_i$ ($1 \le p_i \le m$, $1 \le c_i \le 10^9$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision.

The United Party of Berland has the index $1$.


-----Output-----

Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.


-----Examples-----
Input
1 2
1 100

Output
0

Input
5 5
2 100
3 200
4 300
5 400
5 900

Output
500

Input
5 5
2 100
3 200
4 300
5 800
5 900

Output
600



-----Note-----

In the first sample, The United Party wins the elections even without buying extra votes.

In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $3$, $4$ and $5$ get one vote and party number $2$ gets no votes.

In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.

Difficulty: competition

Starter code:

Solutions:

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n,m=list(map(int,input().split()))

party=[[] for _ in range(m+5)]
pc=sorted([list(map(int,input().split())) for _ in range(n)],key=lambda x:x[1])
choose=[0]*n

for i in range(n):
    party[pc[i][0]].append(i)



want=10**18
for i in range(1,n+1):
    p1=len(party[1])
    # want all other parties to have <i voters
    for j in range(2,m+5):
        if len(party[j])<i: continue
        for k in range(len(party[j])-i+1):
            p1+=1
            choose[party[j][k]]=1
    # want party 1 to have >=i voters
    want2=0
    for j in range(n):
        if p1<i and choose[j]==0 and pc[j][0]!=1:
            choose[j]=1
            p1+=1
        if choose[j]==1:
            want2+=pc[j][1]
    if want>want2:
        want=want2
    #print(i,want2)
    # reset
    choose=[0]*n

print(want)


n,m=list(map(int,input().split()))

men=[]

for i in range(n):
	x,y=list(map(int,input().split()))
	men.append((y,x-1))

def Calc(lim):
	cnt=[0]*m
	vis=[False]*n
	for i in range(n):
		cnt[men[i][1]]+=1
	cost=0
	for i in range(n):
		if men[i][1]!=0 and cnt[men[i][1]]>=lim:
			cnt[men[i][1]]-=1
			cost+=men[i][0]
			vis[i]=True
			cnt[0]+=1
	
	for i in range(n):
		if cnt[0]<lim and vis[i] == False and men[i][1]!=0:
			cnt[0]+=1
			cost+=men[i][0]
	return cost

men.sort()

ans = 10**18

for i in range(n):
	ans=min(ans,Calc(i))

print(ans)


n, m = map(int, input().split()) # voters, parties

money = [0] * n

for i in range(n):
    x, y = map(int, input().split())
    money[i] = (y, x - 1)

money.sort()

def calc(lim):
    visited = [False] * n
    cost = 0

    cnt = [0] * m
    for i in range(n):
        cnt[money[i][1]] += 1

    for i in range(n):
        if money[i][1] != 0 and cnt[money[i][1]] >= lim:
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]
            visited[i] = True

    for i in range(n):
        if cnt[0] >= lim:
            break

        if money[i][1] != 0 and not visited[i]:
            cnt[money[i][1]] -= 1
            cnt[0] += 1
            cost += money[i][0]

    return cost

ans = 10 ** 18

for i in range(n):
    ans = min(ans, calc(i))

print(ans)

import sys
from collections import defaultdict

n, m = map(int, sys.stdin.readline().rstrip('\n').split(' '))

p = defaultdict(list)
for _ in range(n):
	x, y = map(int, sys.stdin.readline().rstrip('\n').split(' '))
	p[x].append(y)

for key in p:
	p[key] = sorted(p[key])

ans = 10**100
for k in range(1, n + 1):
	cur = 0
	r = []
	for key in p:
		if key == 1:
			continue
		a = p[key]
		cnt = max(0, len(a) - (k - 1))
		cur += sum(a[:cnt])
		r += a[cnt:]
	r = sorted(r)
	cnt = max(0, len(r) - (n - k))
	cur += sum(r[:cnt])
	ans = min(ans, cur)
	
print(ans)


class Solver:
    def solve(self):
        self.num_voters, self.num_parties = (int(x) for x in input().split())

        self.votes_per_party = [[] for _ in range(self.num_parties)]

        for _ in range(self.num_voters):
            party, price = (int(x) for x in input().split())
            party -= 1

            self.votes_per_party[party].append(price)

        for party in range(self.num_parties):
            self.votes_per_party[party].sort()

        max_necessary_votes = self.num_voters//2 + 1
        cost = lambda min_votes : self.conversion_price_with_fixed_votes(min_votes)
        return self.ternary_search(cost, 0, max_necessary_votes + 2)

    def ternary_search(self, func, begin, end):
        while begin + 1 < end:
            mid = (begin + end - 1) // 2
            if func(mid) <= func(mid + 1):
                end = mid + 1
            else:
                begin = mid + 1
        return func(begin)

    def conversion_price_with_fixed_votes(self, num_votes):
        current_votes = len(self.votes_per_party[0])
        total_cost = 0

        for votes in self.votes_per_party[1:]:
            if len(votes) >= num_votes:
                num_bought_votes = len(votes) - num_votes + 1
                total_cost += sum(votes[:num_bought_votes])
                current_votes += num_bought_votes

        
        if current_votes >= num_votes:
            return total_cost
        num_votes_to_buy = num_votes - current_votes

        votes_left = []
        for party in range(1, self.num_parties):
            votes_left += self.votes_per_party[party][-(num_votes-1):]
        votes_left.sort()

        return total_cost + sum(votes_left[:num_votes_to_buy])


solver = Solver()
min_price = solver.solve()
print(min_price)



def solve(max_v,votes,m):
    ans = 0
    values = []
    our_v = len(votes[0])
    for i in range(1,m):
        L = len(votes[i])
        if L > max_v:
            take = L-max_v
            our_v += take
            ans += sum(votes[i][:take])
            if take < L:
                values.extend(votes[i][take:])
        else:
            values.extend(votes[i])
    values.sort()
    if our_v <= max_v:
        needed = max_v + 1 - our_v
        if needed <= len(values):
            for i in range(needed):
                ans += values[i]
                our_v += 1
    if our_v <= max_v: return 1<<60
    return ans

n,m = [int(x) for x in input().split()]
votes = [[] for x in range(m)]

for i in range(n):
    p,c = (int(x) for x in input().split())
    p -= 1
    votes[p].append(c)

for i in range(m):
    L = len(votes[i])
    if L > 1:
        votes[i].sort()
lo = 0
hi = n // 2 + 5
while lo < hi:
    mi = lo + (hi-lo)//2
    if solve(mi,votes,m) > solve(mi+1,votes,m) : lo = mi+1
    else: hi = mi
ans = 1<<60
E = 20
for i in range(max(0,lo-E),min(lo+E,n+1)):
    ans = min(ans,solve(i,votes,m))
print(ans)


def solve(max_v,votes,m):
    ans = 0
    values = []
    our_v = len(votes[0])
    for i in range(1,m):
        L = len(votes[i])
        if L > max_v:
            take = L-max_v
            our_v += take
            ans += sum(votes[i][:take])
            if take < L:
                values.extend(votes[i][take:])
        else:
            values.extend(votes[i])
    values.sort()
    if our_v <= max_v:
        needed = max_v + 1 - our_v
        if needed <= len(values):
            for i in range(needed):
                ans += values[i]
                our_v += 1
    if our_v <= max_v: return 1<<60
    return ans

n,m = [int(x) for x in input().split()]
votes = [[] for x in range(m)]

for i in range(n):
    p,c = (int(x) for x in input().split())
    p -= 1
    votes[p].append(c)

for i in range(m):
    L = len(votes[i])
    if L > 1:
        votes[i].sort()
lo = 0
hi = n // 2 + 5
while lo < hi:
    mi = lo + (hi-lo)//2
    if solve(mi,votes,m) > solve(mi+1,votes,m) : lo = mi+1
    else: hi = mi
ans = 1<<60
E = 20
for i in range(max(0,lo-E),min(lo+E,n+1)):
    ans = min(ans,solve(i,votes,m))
print(ans)

import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

n, m = mints()
A = [0]*n
h = [0]*m
for i in range(n):
	a, b = mints()
	A[i] = (b, a-1)
	h[a-1] += 1
A.sort()
r = 1e100
for k in range(1, n+1):
	b = h[::]
	w = [True]*n
	c = 0
	for i in range(n):
		p, id = A[i]
		if id != 0 and b[id] >= k:
			b[0] += 1
			b[id] -= 1
			c += p
			w[i] = False
	for i in range(n):
		p, id = A[i]
		if id != 0 and w[i] and b[0] < k:
			b[0] += 1
			b[id] -= 1
			c += p
			w[i] = False
	#print(b,c)
	r = min(r, c)
print(r)

import sys

def pro():
	return sys.stdin.readline().strip()

def rop():
	return map(int, pro().split())

a, s = rop()
q = [0] * a
w = [0] * s
for i in range(a):
	n, p = rop()
	q[i] = (p, n-1)
	w[n - 1] += 1
q.sort()
t = 1e100
for k in range(1, a + 1):
	p = w[::]
	r = [True] * a
	m = 0
	for i in range(a):
		po, rty = q[i]
		if rty != 0 and p[rty] >= k:
			p[0] += 1
			p[rty] -= 1
			m += po
			r[i] = False
	for i in range(a):
		po, rty = q[i]
		if rty != 0 and r[i] and p[0] < k:
			p[0] += 1
			p[rty] -= 1
			m += po
			r[i] = False
	t = min(t, m)
print(t)

# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 1/29/19

Let's iterate over final number of votes for The United Party of Berland.
We can see that all opponents should get less votes than our party,
and our party should get at least our chosen number of votes.

We can sort all voters by their costs, and solve the problem in two passes.
First, if we need to get 𝑥 votes, we should definitely buy all cheap votes for parties that have at least 𝑥 votes.
Second, if we don't have 𝑥 votes yet, we should by the cheapest votes to get 𝑥 votes.
We can see that this solution is optimal: consider the optimal answer, and see how many votes The United Party got.
We tried such number of votes, and we tried to achieve this number of votes by cheapest way, so we couldn't miss the
optimal answer. This can be implemented in 𝑂(𝑛2log𝑛) or even 𝑂(𝑛log𝑛).



"""

import collections
import time
import os
import sys
import bisect
import heapq


def solve(N, M, A):
    votes = [[] for _ in range(M+1)]
    for p, v in A:
        votes[p].append(v)
    
    for p in range(1, M+1):
        votes[p].sort()
    
    own = len(votes[1])
    votes = votes[2:]
    votes.sort(reverse=True, key=len)
    size = [len(v) for v in votes]
    if not size or own > size[0]:
        return 0
    
    nvotes = len(votes)
    ans = float('inf')
    for buy in range((size[0]-own)//2+1, min(N, (N+1) // 2 + 1) + 1):
        cost = 0
        target = own + buy
        done = 0
        
        for p in range(nvotes):
            if size[p] >= target:
                t = size[p] - target + 1
                cost += sum(votes[p][: t] or [0])
                done += t
            else:
                break
        if done >= buy:
            ans = min(ans, cost)
        else:
            more = buy - done
            q = []
            for p in range(nvotes):
                t = max(size[p] - target + 1, 0)
                q.extend(votes[p][t: t+more])
            q.sort()
            cost += sum(q[:more])
            ans = min(ans, cost)
        
    return ans


N, M = list(map(int, input().split()))
A = []
for i in range(N):
    p, v = list(map(int, input().split()))
    A.append((p, v))

print(solve(N, M, A))