제출 #547972

#제출 시각아이디문제언어결과실행 시간메모리
547972Jarif_RahmanLove Polygon (BOI18_polygon)C++17
100 / 100
199 ms30036 KiB
#include <bits/stdc++.h>
#define pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;

int n;
vector<vector<int>> v;
vector<int> succ;
vector<bool> bl;

pair<int, int> cycle;
bool cycle_type;

void dfs_cycle(int nd, int ss){
    if(bl[nd]){
        cycle = {ss, nd};
        return;
    }
    bl[nd] = 1;
    unordered_map<int, int> mp;
    for(int x: v[nd]) if(x != ss) dfs_cycle(x, nd), mp[x]++;
    for(auto [x, c]: mp) if(c > 1){
        cycle = {nd, x};
        if(nd != x) cycle_type = 1;
    }
}

int mc = 0;

bool dfs(int nd, int ss, bool type){
    bool s = 0;
    for(int x: v[nd])
        if(x != ss && (nd != cycle.f || x != cycle.sc) && (nd != cycle.sc || x != cycle.f))
            s|=dfs(x, nd, type);
    if(ss == -1 && cycle_type) dfs(cycle.sc, nd, type);
    if(type){
        if(nd == cycle.f) return 0;
        if(nd == cycle.sc){
            mc++;
            return 0;
        }
    }
    if(s) mc++;
    return !s;
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n;
    if(n%2 != 0){
        cout << "-1\n";
        exit(0);
    }

    v.assign(n, {});
    succ.assign(n, -1);
    bl.assign(n, 0);
    unordered_map<str, int> mp;
    int in = 0;

    for(int i = 0; i < n; i++){
        str a, b; cin >> a >> b;
        if(mp.find(a) == mp.end()) mp[a] = in, in++;
        if(mp.find(b) == mp.end()) mp[b] = in, in++;  
        succ[mp[a]] = mp[b];
        v[mp[a]].pb(mp[b]);
        v[mp[b]].pb(mp[a]);
    }

    int ans = 0;

    for(int i = 0; i < n; i++){
        if(bl[i]) continue;
        int mx = 0;
        cycle_type = 0;
        dfs_cycle(i, -1);
        mc = 0;
        dfs(cycle.f, -1, 0);
        mx = max(mx, mc);
        if(cycle.f != cycle.sc){
            mc = 0;
            dfs(cycle.f, -1, 1);
            mx = max(mx, mc+cycle_type);
        }
        ans+=mx;
    }

    ans = n-ans;

    cout << ans << "\n";
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...