#include <bits/stdc++.h>
using namespace std;
template <class T>
T &get(T &n) {
  cin >> n;
  return n;
}
const int hell = 1000000007;
const long long INF = (long long)hell * hell;
vector<int> compression;
int get_value(int N) {
  assert(compression.size() >= N);
  return compression[N - 1];
}
int get_index(int N) {
  auto it = lower_bound(compression.begin(), compression.end(), N);
  assert((*it) == N);
  return 1 + (int)(it - compression.begin());
}
struct result {
  int nodes = 1;
  int edges = 0;
  int maxNode;
  int secondMaxNode;
  result(int N) {
    nodes = 1;
    edges = 0;
    maxNode = N;
    secondMaxNode = -1;
  }
  void computeNewMax(int val) {
    if (maxNode < val) {
      secondMaxNode = maxNode;
      maxNode = val;
    } else if (secondMaxNode < val) {
      secondMaxNode = val;
    }
  }
};
struct Graph {
  vector<vector<int> > adj;
  vector<result> nodesAndEdges;
  vector<bool> visit;
  int N;
  Graph(int M) {
    N = M;
    adj.resize(N + 1);
  }
  void add_edge(int p, int q) {
    adj[p].push_back(q);
    adj[q].push_back(p);
  }
  result dfs(int node) {
    assert(visit[node] == false);
    visit[node] = true;
    result res(get_value(node));
    for (int child : adj[node]) {
      ;
      res.edges += 1;
      if (!visit[child]) {
        auto ans = dfs(child);
        res.nodes += ans.nodes;
        res.edges += ans.edges;
        res.computeNewMax(ans.maxNode);
        res.computeNewMax(ans.secondMaxNode);
      }
    }
    return res;
  }
  int solve() {
    visit.resize(N + 1);
    fill(visit.begin(), visit.end(), false);
    long long ans = 0;
    bool poss = true;
    for (int i = 1; i <= N; ++i) {
      if (!visit[i]) {
        auto X = dfs(i);
        X.edges >>= 1;
        int days = X.nodes, exams = X.edges;
        ;
        assert(X.edges >= X.nodes - 1);
        if (exams == days) {
          ans += X.maxNode;
        } else if (exams == days - 1) {
          ans += X.secondMaxNode;
        } else {
          poss = false;
        }
      }
    }
    if (poss)
      return ans;
    else
      return -1;
  }
};
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int N;
  cin >> N;
  vector<pair<int, int> > e;
  for (int i = 0; i < N; ++i) {
    int a, b;
    cin >> a >> b;
    e.push_back(make_pair(a, b));
    compression.push_back(a);
    compression.push_back(b);
  }
  sort(compression.begin(), compression.end());
  compression.erase(unique(compression.begin(), compression.end()),
                    compression.end());
  ;
  Graph G(compression.size());
  for (auto edge : e) {
    G.add_edge(get_index(edge.first), get_index(edge.second));
  }
  cout << G.solve();
}
