답안 #944212

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
944212 2024-03-12T11:01:26 Z LucaIlie Love Polygon (BOI18_polygon) C++17
0 / 100
114 ms 16664 KB
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e5;
int n;
bool vis[MAX_N + 1], isOnCycle[MAX_N + 1], isUnpaired[MAX_N + 1];
int repr[MAX_N + 1], parent[MAX_N + 1], sizee[MAX_N + 1], dp[MAX_N + 1];
vector<int> adj[MAX_N + 1];
unordered_map<string, int> nameToId;

void findCycles( int u, int r ) {
    repr[u] = r;
    for ( int v: adj[u] ) {
        if ( repr[v] == r ) {
            isOnCycle[u] = true;
            return;
        }

        if ( repr[v] == 0 )
            findCycles( v, r );

        if ( isOnCycle[v] ) {
            isOnCycle[u] = true;
            return;
        }
    }
}

void detectCycles() {
    for ( int v = 1; v <= n; v++ )
        vis[v] = false;

    for ( int v = 1; v <= n; v++ ) {
        if ( vis[v] )
            continue;
        findCycles( v, v );
    }
}

void calc( int u ) {
    int odd = 0;
    sizee[u] = 1;
    for ( int v: adj[u] ) {
        if ( isOnCycle[v] )
            continue;

        calc( v );

        dp[u] += dp[v];
        sizee[u] += sizee[v];
        if ( sizee[v] % 2 == 1 )
            odd++;
    }
    dp[u] += odd;
}

int main() {
    cin >> n;
    int id = 0;
    for ( int i = 0; i < n; i++ ) {
        string s, t;
        cin >> s >> t;
        nameToId[s] = (nameToId[s] == 0 ? ++id : nameToId[s]);
        nameToId[t] = (nameToId[t] == 0 ? ++id : nameToId[t]);
        parent[nameToId[s]] = nameToId[t];
        adj[nameToId[t]].push_back( nameToId[s] );
        //cout << nameToId[s] << " " << nameToId[t] << "\n";
    }

    if ( n % 2 == 1 ) {
        cout << -1 << "\n";
        return 0;
    }

    detectCycles();

    int ans = 0;
    for ( int u = 1; u <= n; u++ ) {
        if ( !isOnCycle[u] )
            continue;

        calc( u );
        ans += dp[u];
        if ( sizee[u] % 2 == 1 )
            isUnpaired[u] = true;
    }

    for ( int v = 1; v <= n; v++ ) {
        if ( isUnpaired[v] && isUnpaired[parent[v]] ) {
            isUnpaired[v] = isUnpaired[parent[v]] = false;
            if ( parent[parent[v]] != v )
                ans++;
        }
    }
    for ( int v = 1; v <= n; v++ ) {
        if ( isUnpaired[parent[v]] )
            ans++;
    }

    cout << ans << "\n";

    return 0;
}
# 결과 실행 시간 메모리 Grader output
1 Correct 1 ms 2648 KB Output is correct
2 Correct 1 ms 2652 KB Output is correct
3 Incorrect 1 ms 2652 KB Output isn't correct
4 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 1 ms 2652 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 114 ms 16664 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Correct 1 ms 2648 KB Output is correct
2 Correct 1 ms 2652 KB Output is correct
3 Incorrect 1 ms 2652 KB Output isn't correct
4 Halted 0 ms 0 KB -