-
Notifications
You must be signed in to change notification settings - Fork 0
/
FROGV(union_find).cpp
100 lines (94 loc) · 1.36 KB
/
FROGV(union_find).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
#include <bits/stdc++.h>
#define M 100003
using namespace std;
typedef long long ll;
struct frog
{
int val;
int pos;
frog(int v , int pos) : val(v) , pos(pos)
{
}
};
bool cmp(frog a , frog b)
{
return (a.val < b.val);
}
class Disjset
{
private:
vector<int> s;
public:
Disjset(int num)
{
for(int i=0;i<num;i++)
s.push_back(-1);
}
int find(int x) // non-recursive
{
if(s[x]<0) // for recursive in else - return s[x] = find(s[x])
return x;
int y = x;
for( ; s[y]>0; y=s[y]);
int z = y;
for( ; x!=z ; x=y)
{
y = s[x];
s[x] = z;
}
return z;
}
void dounion( int root1,int root2)
{
root1 = find(root1);
root2 = find(root2);
if(root1 == root2)
return ;
if(s[root1]>=s[root2])
{
s[root2]+=s[root1];
s[root1]=root2;
}
else
{
s[root1]+=s[root2];
s[root2]=root1;
}
}
void show()
{
int num=s.size();
for(int i=0;i<num;i++)
cout<<i<<"-> "<<s[i]<<endl;
}
};
int main()
{
Disjset ds(M);
int N , K , P;
int a , b;
cin>>N>>K>>P;
vector<frog> v;
for(int i = 0 ; i<N ; i++)
{
cin>>a;
v.push_back(frog(a,i+1));
}
sort(v.begin() , v.end() , cmp);
for(int i = 1 ; i<N ; i++)
{
if(v[i].val - v[i-1].val <= K)
{
ds.dounion(v[i].pos , v[i-1].pos);
}
}
while(P--)
{
cin>>a>>b;
if(ds.find(a) == ds.find(b))
cout<<"Yes";
else
cout<<"No";
cout<<endl;
}
}