-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEE17BTECH11002_7.cpp
188 lines (175 loc) · 2.44 KB
/
EE17BTECH11002_7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
#include <limits.h>
using namespace std;
typedef struct node
{
int key;
int rank;
struct node *parent;
}Node;
typedef struct arr
{
Node *root;
}Head;
Node* newnode(int k)
{
Node *temp=new Node;
temp->key=k;
temp->rank=1;
temp->parent=temp;
return temp;
}
class set
{
public:
int n;
Head *h;
set(int num) //constructor
{
n=num;
h= new Head[n+1];
for(int i=1;i<n+1;i++)
{
h[i].root=newnode(i);
}
}
Node* find(int k)
{
Node *temp;
for(int i=1;i<n+1;i++)
{
if(h[i].root->key==k)
{
temp=h[i].root;
break;
}
else
{temp=NULL;}
}
if(temp!=NULL)
{
while(temp->parent!=temp)
{
temp=temp->parent;
}
return temp;
}
return temp;
}
int check(int a,int b)
{
int c=0;
if(a<=0 || b<=0)
{return -1;}
else
{
for(int i=1;i<n+1;i++)
{
if(h[i].root->key==a || h[i].root->key==b)
{c++;}
}
if(c!=2)
{return -1;}
else if(find(a)==find(b))
{return 1;}
else if(find(a)!=find(b))
{return 0;}
}
}
void Union(int a,int b)
{
if((a <= n) && (b<=n) && (a>0) && (b>0))
{
Node *ra=find(a);
Node *rb=find(b);
if(ra->rank==rb->rank)
{
rb->parent=ra;
ra->rank++;
}
else if(ra->rank>rb->rank)
{rb->parent=ra;}
else
{ra->parent=rb;}
}
else
{}
}
Node *Rank(int a)
{
for(int i=1;i<n+1;i++)
{
if(h[i].root->key==a)
{return h[i].root;}
}
return NULL;
}
};
int i=0;
int main()
{
while(!cin.eof())
{
string s;
getline(cin,s);
istringstream iss;
iss.str(s);
string vals;
iss>>vals;
set *p;
if(vals=="N")
{
//cout << i << endl;
if(i!=0)
{delete p;}
iss>>vals;
int n=stoi(vals);
p=new set(n);
i=1;
}
else if(vals=="?")
{
iss>>vals;
int a=stoi(vals);
iss>>vals;
int b=stoi(vals);
int out=p->check(a,b);
cout << out << endl;
}
else if(vals=="S")
{
iss>>vals;
int a=stoi(vals);
Node *pa=p->find(a);
if(pa!=NULL)
{cout << pa->key << endl;}
else
{cout << "-1" << endl;}
}
else if(vals=="U")
{
iss>>vals;
int a=stoi(vals);
iss>>vals;
int b=stoi(vals);
p->Union(a,b);
}
else if(vals=="R")
{
iss>>vals;
int a=stoi(vals);
Node *temp=p->Rank(a);
if(temp!=NULL)
{cout << temp->rank << endl;}
else
{cout << "-1" <<endl;}
}
}
}