1) Merges two disjoint sets into one
2) Retrieves the representative element of a set
3) 3
4) 2
5) [0, 1, 1, 1, 4, 5]
6) To make the findSet operation faster by reducing the depth of the tree.
7) 45
8) option 2
Q1:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
unordered_map<int, int> mp;
vector<int> ar(n);
for (int i = 0; i < n; i++) {
cin >> ar[i];
mp[ar[i]] = i;
}
int swaps = 0;
n=n/2;
for (int i = 0; i < 2 * n; i += 2) {
int first_star = ar[i];
int twin = first_star ^ 1;
if (ar[i + 1] != twin) {
int twin_pos = mp[twin];
swap(ar[i + 1], ar[twin_pos]);
mp[ar[twin_pos]] = twin_pos;
mp[ar[i + 1]] = i + 1;
swaps++;
}
}
cout << swaps;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
if(t!=0)cout<< "\n";
}
}
Q2:
#include <bits/stdc++.h>
using namespace std;
void solve() {
int m, n;
cin >> m >> n;
vector<string> board(m);
for (int i = 0; i < m; i++) {
cin >> board[i];
}
vector<vector<bool>> visited(m, vector<bool>(n, false));
queue<pair<int, int>> q;
// Directions for moving up, down, left, and right
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
// Mark all 'O's connected to the boundary as safe
auto mark_safe = [&](int x, int y) {
if (visited[x][y] || board[x][y] == 'X') return;
visited[x][y] = true;
q.push({x, y});
};
// Add boundary 'O's to the queue
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') mark_safe(i, 0);
if (board[i][n - 1] == 'O') mark_safe(i, n - 1);
}
for (int j = 0; j < n; j++) {
if (board[0][j] == 'O') mark_safe(0, j);
if (board[m - 1][j] == 'O') mark_safe(m - 1, j);
}
// BFS to mark all safe 'O's
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny] &&
board[nx][ny] == 'O') {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
// Capture all unmarked 'O's
int remaining_Os = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O' && !visited[i][j]) {
board[i][j] = 'X';
}
if (board[i][j] == 'O') remaining_Os++;
}
}
cout << remaining_Os << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}