S SmartDocs
系列: Algorithms cpp 68 行 · 更新於 2026-04-05

battle_ship.cpp

Algorithms/battle_ship.cpp

#include <iostream>
#include <cmath>
using namespace std;

const int MAX_N = 30001;

int parent[MAX_N];
long long dist[MAX_N];  // distance to the root
long long sz[MAX_N];   // size of the group for root

// Path compression find, and sum the distances to the root
int find(int x) {
    if (parent[x] == x) return x;

    int root = find(parent[x]);
    dist[x] += dist[parent[x]];
    parent[x] = root;
    return root;
}

// Merge: move i-th battle ship to the j-th battle ship
void merge(int i, int j) {
    int ri = find(i);
    int rj = find(j);

    // If i and j are already in the same group, do nothing
    // Otherwise, move i to the group of j
    dist[ri] = sz[rj];  // the start point of ri = rj column size
    sz[rj] += sz[ri];   // rj column size += ri column size
    parent[ri] = rj;    // ri's parent = rj
}

int main() {

    // Initialize the parent and dist arrays
    for (int i = 1; i < MAX_N; i++) {
        parent[i] = i;
        dist[i] = 0;
        sz[i] = 1;
    }

    int n;
    cin >> n;

    while (n--) {
        char op;
        int i, j;
        cin >> op >> i >> j;

        if (op == 'M') {
            merge(i, j);
        } else {
            // C i j
            int ri = find(i);
            int rj = find(j);

            if (ri != rj) {
                cout << -1 << endl;
            }
            else {
                // dist[i] and dist[j] are the same root.
                long long ans = abs(dist[i] - dist[j])- 1;
                cout << ans << endl;
            }
        }
    }
    return 0;
}

相關文章