forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
186.cpp
71 lines (60 loc) · 1.48 KB
/
186.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
// C++ program to rearrange a string so that all same
// characters become at least d distance away using STL
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
typedef pair<char, int> PAIR;
// Comparator of priority_queue
struct cmp {
bool operator()(const PAIR& a, const PAIR& b)
{
if(a.second < b.second) return true;
else if(a.second > b.second) return false;
else return a.first > b.first;
}
};
void rearrange(char* str, int d)
{
// Length of the string
int n = strlen(str);
// A structure to store a character and its frequency
unordered_map<char, int> m;
// Traverse the input string and store frequencies of
// all characters.
for (int i = 0; i < n; i++) {
m[str[i]]++;
str[i] = '\0';
}
// max-heap
priority_queue<PAIR, vector<PAIR>, cmp> pq(m.begin(),
m.end());
// Now one by one extract all distinct characters from
// heap and put them back in str[] with the d
// distance constraint
while (pq.empty() == false) {
char x = pq.top().first;
// Find the first available position in str[]
int p = 0;
while (str[p] != '\0')
p++;
// Fill x at p, p+d, p+2d, .. p+(frequency-1)d
for (int k = 0; k < pq.top().second; k++) {
// If the index goes beyond size, then string
// cannot be rearranged.
if (p + d * k >= n) {
cout << "Cannot be rearranged";
exit(0);
}
str[p + d * k] = x;
}
pq.pop();
}
}
// Driver Code
int main()
{
char str[] = "aabbcc";
// Function call
rearrange(str, 3);
cout << str;
}