#include<iostream>
#include<queue>
using namespace std;

#define int long long

const int N = 5 * 1e5 + 5;
int n;
struct node{
	int x, c;
}a[N];
int mx[N];

signed main(){
	cin.tie(0) -> ios::sync_with_stdio(0);
	cin >> n;
	
	for(int i = 1;i <= n;i ++){
		cin >> a[i].x >> a[i].c;
		mx[a[i].c] = max(a[i].x, mx[a[i].c]);
	}
	
	int mxid = 0, maxx = -4e9, cnt = 0;
	for(int i = 1;i <= n;i ++){
		if(mx[i] > maxx){
			maxx = mx[i];
			mxid = i;
		}
	}
	int elmx = -4e9;
	for(int i = 1;i <= n;i ++){
		if(a[i].c != mxid){
			elmx = max(elmx, a[i].x);
		}
	}
	if(elmx == -4e9){
		cout << 0 << '\n';
		return 0;
	}
	int ans = 0;
	for(int i = 1;i <= n;i ++){
		if(a[i].c == mxid && a[i].x != maxx && elmx + a[i].x >= 0){
			ans += elmx + a[i].x;
		}
	}
	for(int i = 1;i <= n;i ++){
		if(a[i].c != mxid && a[i].x + maxx >= 0){
			ans += (a[i].x + maxx);
		}
	}
	cout << ans << '\n';
	return 0;
}

