Serie: Algorithms
cpp
68 líneas
· Actualizado 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;
}
Artículos relacionados
Algorithms
java
Actualizado 2026-03-02
#include <iostream>.java
#include <iostream>.java — java source code from the Algorithms learning materials (Algorithms/#include <iostream>.java).
Leer artículo →
Algorithms
cpp
Actualizado 2026-04-07
748.cpp
748.cpp — cpp source code from the Algorithms learning materials (Algorithms/748.cpp).
Leer artículo →
Algorithms
cpp
Actualizado 2026-04-07
827.cpp
827.cpp — cpp source code from the Algorithms learning materials (Algorithms/827.cpp).
Leer artículo →
Algorithms
cpp
Actualizado 2026-04-07
827_best_greedy.cpp
827_best_greedy.cpp — cpp source code from the Algorithms learning materials (Algorithms/827_best_greedy.cpp).
Leer artículo →
Algorithms
cpp
Actualizado 2026-04-07
8402.cpp
8402.cpp — cpp source code from the Algorithms learning materials (Algorithms/8402.cpp).
Leer artículo →
Algorithms
cpp
Actualizado 2026-04-07
860.cpp
860.cpp — cpp source code from the Algorithms learning materials (Algorithms/860.cpp).
Leer artículo →