-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevilstraw.cc
More file actions
101 lines (73 loc) · 2.18 KB
/
evilstraw.cc
File metadata and controls
101 lines (73 loc) · 2.18 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
95
96
97
98
99
100
101
// William Sjöblom
#include <cstdio>
#include <string>
#include <iterator>
#include <algorithm>
#include <cmath>
#include <limits>
#include <iostream>
const int INT_MAX = std::numeric_limits<int>::max();
using It = std::string::iterator;
using RIt = std::string::reverse_iterator;
template<typename Iterator>
int swap(std::string& s, Iterator it, Iterator target) {
int distance = std::distance(it, target);
char c = *it;
s.erase(it);
s.insert(target, c);
return std::abs(distance);
}
It find_first(std::string& s, It first, It last, char c) {
while (first != last) {
if (*first == c) return first;
first++;
}
return s.end();
}
It find_last(std::string& s, It last, It first, char c) {
while (first != last) {
if (*last == c) return last;
last--;
}
return s.end();
}
int solve(std::string s) {
int swaps = 0;
auto left = s.begin();
auto right = s.end() - 1;
while (std::distance(left, right) > 0) {
if (*left != *right) {
auto inner_left = std::next(left);
auto inner_right = std::prev(right);
auto first = find_first(s, inner_left, right, *right);
auto last = find_last(s, inner_right, left, *left);
int first_distance = std::distance(left, first);
int last_distance = std::distance(right, last);
if (first == s.end()) first_distance = INT_MAX;
if (last == s.end()) last_distance = INT_MAX;
if (first_distance < last_distance) {
swaps += swap(s, first, left);
} else if (last_distance != INT_MAX && first_distance >= last_distance) {
swaps += swap(s, last, right);
} else {
return -1;
}
}
left++;
right--;
}
return swaps;
}
int main() {
int test_count;
scanf("%d\n", &test_count);
while (test_count--) {
char s[1000 + 1];
scanf("%s\n", s);
int result = solve(s);
if (result == -1)
printf("Impossible\n");
else
printf("%d\n", result);
}
}