Submission #1354029

#TimeUsernameProblemLanguageResultExecution timeMemory
1354029AksLolCodingLove Polygon (BOI18_polygon)C++17
100 / 100
78 ms10540 KiB
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e18;

const int N = 200005;

int n, love[N], in_degree[N];
bool matched[N];

map<string, int> ids;
int c = 0;
int get_id(string &s) {
    int &id = ids[s];
    if (id == 0) id = ++c;
    return id;
}

signed main() {
  cin.tie(0)->sync_with_stdio(0);
  cin >> n;
  if (n % 2 != 0) {
    cout << "-1\n";
    return 0;
  }

  for (int i = 1; i <= n; i++) {
    string u_s, v_s;
    cin >> u_s >> v_s;
    int u = get_id(u_s), v = get_id(v_s);
    love[u] = v;
  }

  int couples = 0;
  for (int i = 1; i <= n; i++) {
    if (!matched[i]) {
      int j = love[i];
      if (i != j && love[j] == i) {
        matched[i] = true;
        matched[j] = true;
        couples += 2;
      }
    }
  }

  for (int i = 1; i <= n; i++) {
    if (!matched[i]) in_degree[love[i]]++;
  }

  queue<int> q;
  for (int i = 1; i <= n; i++) {
    if (in_degree[i] == 0 and !matched[i]) q.push(i);
  }

  while (!q.empty()) {
    int u = q.front();
    q.pop();
    if (matched[u]) continue;

    int v = love[u];
    if (!matched[v]) {
      matched[u] = true;
      matched[v] = true;
      couples++;
      int T1 = love[v];
      if (matched[T1]) continue ;
      in_degree[T1]--;
      if (in_degree[T1] == 0 ) q.push(T1);
    }

  }

  for (int i = 1; i <= n; i++) {
    if (!matched[i]) {
      int curr = i, siz = 0;
      while (!matched[curr]) {
        matched[curr] = true;
        curr = love[curr];
        siz++;
      }
      couples += (siz / 2);
    }
  }


  int res = n - couples;
  cout << res << '\n';
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...