-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP10098.cpp
More file actions
94 lines (78 loc) · 1.94 KB
/
P10098.cpp
File metadata and controls
94 lines (78 loc) · 1.94 KB
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
#include <stdio.h>
#include <iostream>
#include <set>
#include <algorithm>
struct PermutationNode {
PermutationNode *next;
char val;
};
struct PermutationHandler {
PermutationNode *nodes;
PermutationHandler() : nodes(NULL) {}
void reset(const std::string &word) {
if(nodes != NULL)
delete[] nodes;
nodes = new PermutationNode[word.size()+1];
for(unsigned int i = 0; i < word.size(); ++i) {
nodes[i+1].val = word[i];
nodes[i].next = &(nodes[i+1]);
}
nodes[word.size()].next = NULL;
}
PermutationNode* root() {
return &(nodes[0]);
}
};
void run(const unsigned int i, PermutationHandler &ph, std::string &word) {
if(i == word.size()-1) {
char letter = ph.root()->next->val;
word[i] = letter;
std::cout << word << std::endl;
return;
}
// try all combinations:
PermutationNode *node = ph.root();
char prevChar = ' ';
while(node->next != NULL) {
PermutationNode *n = node->next;
// remove n from permutation:
node->next = n->next;
char currentChar = n->val;
word[i] = currentChar;
if(currentChar != prevChar) { // ensure we don't repeat ;)
run(i+1, ph, word);
prevChar = currentChar;
}
// re-insert in permutation and go to next:
node->next = n; // n->next is already set (never changes)
node = n;
}
}
bool ffs(char a,char b) {
if(('a' <= a && a <= 'z' && 'a' <= b && b <= 'z') || ('A' <= a && a <= 'Z' && 'A' <= b && b <= 'Z'))
return a < b;
if('a' <= a && a <= 'z') {
a -= 'a'-'A';
if(a == b)
return false;
return a < b;
}
b -= 'a'-'A';
if(a == b)
return true;
return a < b;
}
int main() {
std::string line;
PermutationHandler ph;
int lines;
std::cin >> lines;
for(int ignore = 0; ignore < lines; ++ignore) {
std::cin >> line;
std::sort(&line[0], &line[line.size()], ffs);
ph.reset(line);
run(0, ph, line);
std::cout << std::endl;
}
return 0;
}