-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathL.cpp
110 lines (84 loc) · 2.29 KB
/
L.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
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const size_t alphabet = 256;
string kthShift(const string& s, int k) {
size_t n = s.size();
vector<int> classes(n), pm(n), count(max(n, alphabet));
for (int i = 0; i < n; ++i) {
count[s[i]]++;
}
for (int i = 1; i < alphabet; ++i) {
count[i] += count[i - 1];
}
for (int i = 0; i < n; ++i) {
pm[--count[s[i]]] = i;
}
classes[pm[0]] = 0;
int numberCl = 1;
for (int i = 1; i < n; i++) {
if (s[pm[i]] != s[pm[i - 1]]) {
numberCl++;
}
classes[pm[i]] = numberCl - 1;
}
vector<int> npm(n), nclasses(n);
for (int j = 0; (1 << j) < n; ++j) {
int len = 1 << j;
for (int i = 0; i < n; ++i) {
npm[i] = pm[i] - len;
if (npm[i] < 0) {
npm[i] += n;
}
}
fill(count.begin(), count.begin() + numberCl, 0);
for (int i = 0; i < n; ++i) {
count[classes[npm[i]]]++;
}
for (int i = 1; i < numberCl; ++i) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
pm[--count[classes[npm[i]]]] = npm[i];
}
nclasses[pm[0]] = 0;
numberCl = 1;
for (int i = 1; i < n; ++i) {
pair<int, int> current = {classes[pm[i]], classes[(pm[i] + (1 << j)) % n]};
pair<int, int> prev = {classes[pm[i - 1]], classes[(pm[i - 1] + (1 << j)) % n]};
if (current != prev) {
numberCl++;
}
nclasses[pm[i]] = numberCl - 1;
}
classes.swap(nclasses);
}
vector<int> used(n, false);
int cur = -1;
if (k >= n) {
return "IMPOSSIBLE";
}
for (int i = 0; i < n; ++i) {
if (!used[classes[pm[i]]]) {
used[classes[pm[i]]] = true;
cur++;
}
if (cur == k) {
string res = s.substr(pm[i], n - (pm[i])) + s.substr(0, pm[i]);
return res;
}
}
return "IMPOSSIBLE";
}
int main() {
freopen("shifts.in", "r", stdin);
freopen("shifts.out", "w", stdout);
ios_base::sync_with_stdio(false);
string s;
int k;
cin >> s >> k;
k--;
cout << kthShift(s, k);
return 0;
}