AC code:
#include<bits/stdc++.h>
using namespace std;
int n = 0,m = 0,x = 0,y = 0;
typedef long long LL;
LL ans = 1e18;
multiset<int> v,p[3005];
int main(){
scanf("%d %d",&n,&m);
for(int i = 0;i < n;++i){
scanf("%d %d",&x,&y);
p[x].insert(y);
if(x != 1){
v.insert(y);
}
}
int tkn = 0;
LL rem = 0;
for(int i = n;i >= 1;--i){
for(int j = 2;j <= m;++j){
if(p[j].size() < i){
continue;
}
while(p[j].size() >= i){
++tkn;
rem += *(p[j].begin());
v.erase(v.find(*p[j].begin()) );
p[j].erase(p[j].begin());
}
}
LL res = rem;
int cnt = i - (int)p[1].size() - tkn;
for(auto a : v){
if(cnt <= 0){
break;
}
res += a;
--cnt;
}
ans = min(res,ans);
}
printf("%I64d\n",ans);
return 0;
}