-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_ThreeWayPartitioning.cpp
115 lines (92 loc) · 2.29 KB
/
GFG_ThreeWayPartitioning.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
/*
https://practice.geeksforgeeks.org/problems/three-way-partitioning/1#
Three way partitioning
*/
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
//Function to partition the array around the range such
//that array is divided into three parts.
void threeWayPartition(vector<int>& array,int a, int b)
{
int l=0;
int h=array.size()-1;
int m=0;
while(m<=h)
{
if(array[m] < a)
swap(array[m++], array[l++]);
else if(array[m] > b)
swap(array[m], array[h--]);
else
m++;
}
}
};
// { Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--)
{
int N;
cin>>N;
vector<int> array(N);
unordered_map<int,int> ump;
for(int i=0;i<N;i++){
cin>>array[i];
ump[array[i]]++;
}
int a,b;
cin>>a>>b;
vector<int> original = array;
int k1=0,k2=0,k3=0;
int kk1=0;int kk2=0;int kk3=0;
for(int i=0; i<N; i++)
{
if(original[i]>b)
k3++;
else if(original[i]<=b and original[i]>=a)
k2++;
else if(original[i]<b)
k1++;
}
Solution ob;
ob.threeWayPartition(array,a,b);
for(int i=0;i<k1;i++)
{
if(array[i]<b)
kk1++;
}
for(int i=k1;i<k1+k2;i++)
{
if(array[i]<=b and array[i]>=a)
kk2++;
}
for(int i=k1+k2;i<k1+k2+k3;i++)
{
if(array[i]>b)
kk3++;
}
bool ok = 0;
if(k1==kk1 and k2 ==kk2 and k3 == kk3)
ok = 1;
for(int i=0;i<array.size();i++)
ump[array[i]]--;
for(int i=0;i<array.size();i++)
if(ump[array[i]]!=0)
ok=0;
if(ok)
cout<<1<<endl;
else
cout<<0<<endl;
}
return 0;
}
// } Driver Code Ends