import heapq class UnionFind: def __init__(self, n): self.par = [i for i in range(n+1)] self.rank = [0] * (n+1) self.size = [1 for _ in range(n+1)] # 検索 def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] # 併合 def union(self, x, y): x = self.find(x) y = self.find(y) if self.rank[x] < self.rank[y]: self.par[x] = y self.size[y] += self.size[x] else: self.par[y] = x self.size[x] += self.size[y] if self.rank[x] == self.rank[y]: self.rank[x] += 1 # 同じ集合に属するか判定 def same_check(self, x, y): return self.find(x) == self.find(y) n = int(input()) cd = [[int(i) for i in input().split()] for j in range(n)] c = [] #d = [] ans = 0 for i in range(n): c.append([cd[i][0],n,i]) if i != 0: c.append([cd[i][1],0,i-1]) ans += cd[i][0] ki = UnionFind(n+1) c.sort() #print(c) for i in range(2*n-1): cost,tmp,v = c[i] if tmp == n: if not ki.same_check(n,v): ki.union(n,v) ans += cost #print(v,cost) else: if not ki.same_check(v,v+1): ki.union(v+1,v) ans += cost #print(v,cost) print(ans)