HackerEarth Group Range problem solution

In this HackerEarth Group Range problem solution, You are given N integers. You are required to perform Q queries. In each query, you are given two integers x and y. Your task is to merge the groups that contain the xth and yth integer into a single group. After performing each query, you are required to print the range of numbers that lie in the newly-formed group. Initially, the numbers do not belong to any group.

HackerEarth Group Range problem solution

HackerEarth Group Range problem solution.

using namespace std;
#define ll long long
#define si(x) scanf("%d", &x)
#define sc(x) scanf("%c", &x)
#define sl(x) scanf("%lld", &x)
#define pl(x) printf("%lld\n", x)
#define pi(x) printf("%d\n", x)
#define gu getchar_unlocked
#define pu putchar_unlocked
#define setbits __builtin_popcountll
#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define speed ios::sync_with_stdio(false)

int parent[2 * 100005];
int size[2 * 100005];
int group_min[2 * 100005];
int group_max[2 * 100005];
int arr[2 * 100005];

void setupDS(int n){
for(int i = 1; i <= n; i++){
parent[i] = i;
size[i] = 1;
group_min[i] = arr[i];
group_max[i] = arr[i];

int rootDS(int A){
int num = A;
while(parent[num] != num){
parent[num] = parent[parent[num]];
num = parent[num];
return num;

void unionDS(int A, int B){
int rootA = rootDS(A);
int rootB = rootDS(B);
if(size[rootA] < size[rootB]){
parent[rootA] = parent[rootB];
size[rootB] += size[rootA];
group_max[rootB] = max(group_max[rootB], group_max[rootA]);
group_min[rootB] = min(group_min[rootB], group_min[rootA]);
parent[rootB] = parent[rootA];
size[rootA] += size[rootB];
group_max[rootA] = max(group_max[rootB], group_max[rootA]);
group_min[rootA] = min(group_min[rootB], group_min[rootA]);

int main(){
int n, i;
for(i = 1; i <= n; i++){
int q;
int x, y;
si(x); si(y);
if(rootDS(x) == rootDS(y)){
cout<<group_min[rootDS(x)]<<" "<<group_max[rootDS(x)]<<endl;
unionDS(x, y);
cout<<group_min[rootDS(x)]<<" "<<group_max[rootDS(x)]<<endl;

Post a Comment