Ambigramm

  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
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
#define FileName "ambigram"
#define maxn 50
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
char gch[] = "HIMNOSXZW", gchp[] = "HIWNOSXZM"; // 9
int dist(char c1, char c2) {
return abs(c1 - c2);
}
int dele(char c) {
return Min(abs('A' - c), abs('Z' - c)) + 1;
}
int ansd[maxn][maxn];
string anss[maxn][maxn];
void bet(int b, int e, int nd, string ns) {
if (ansd[b][e] < nd) return;
if (ansd[b][e] > nd) {
ansd[b][e] = nd;
anss[b][e] = ns;
return;
}
if (anss[b][e].length() > ns.length()) return;
if (anss[b][e].length() < ns.length()) {
anss[b][e] = ns;
return;
}
if (strcmp(anss[b][e].c_str(), ns.c_str()) <= 0) return ;
anss[b][e] = ns;
}
char s[maxn+2];
int main(void)
{
int n;
freopen(FileName".in", "r", stdin);
freopen(FileName".out", "w", stdout);
gets(s);
n = strlen(s);
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++) {
ansd[i][j] = 0;
anss[i][j] = string("");
}
for (int i = 0; i < n; i++) {
ansd[i][i] = dele(s[i]);
anss[i][i] = string("");
for (int j = 8; j >= 0; j--)
if (ansd[i][i] >= dist(s[i], gch[j])) {
ansd[i][i] = dist(s[i], gch[j]);
anss[i][i] = string(1, gch[j]);
}
}
for (int l = 2; l <= n; l++) {
for (int i = 0; i+l <= n; i++) {
ansd[i][i+l-1] = 10000;
anss[i][i+l-1] = string("");
bet(i, i+l-1, ansd[i][i+l-2] + dele(s[i+l-1]), anss[i][i+l-2]);
bet(i, i+l-1, ansd[i+1][i+l-1] + dele(s[i]), anss[i+1][i+l-1]);
for (int j = 0; j < 9; j++) {
bet(i, i+l-1, ansd[i+1][i+l-2] + dist(s[i], gch[j]) + dist(s[i+l-1], gchp[j]),
string(1, gch[j]) + anss[i+1][i+l-2] + string(1, gchp[j]));
}
}
}
if (anss[0][n-1].length() == 0) {
int c = 1000;
char ans = 'Z';
for (int i = 0; i < n; i++)
for (int j = 0; j < 9; j++) {
if (gch[j] != gchp[j]) continue;
if (dist(s[i], gch[j]) - dele(s[i]) < c) {
c = dele(s[i]) - dist(s[i], gch[j]);
ans = gch[j];
}
if (dist(s[i], gch[j]) - dele(s[i]) == c) {
if (ans > gch[j]) {
ans = gch[j];
}
}
}
printf("%c\n", ans);
return 0;
}
printf("%s\n", anss[0][n-1].c_str());
return 0;
}