Решение задачи "Амбиграммы". Условие: http://slil.ru/27240766

 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
import java.math.*;
import java.io.*;
import java.util.*;
class Main {
static int maxn=50;
static String first="HIMNOSXZW", next="HIWNOSXZM";
static int[][] answerInt=new int[maxn][maxn];
static String[][] answerString=new String[maxn][maxn];
static String s;
public static int max(int a, int b) {
return (a>b)?a:b;
}
public static int min(int a, int b) {
return (a<b)?a:b;
}
public static int distance(char c1, char c2) {
return Math.abs(c1-c2);
}
public static int remove(char c) {
return min(Math.abs('A'-c), Math.abs('Z'-c))+1;
}
public static void bet(int b, int e, int nd, String ns) {
if(answerInt[b][e]<nd) return;
if(answerInt[b][e]>nd) {
answerInt[b][e]=nd;
answerString[b][e]=ns;
return;
}
if(answerString[b][e].length()>ns.length()) return;
if(answerString[b][e].length()<ns.length()) {
answerString[b][e]=ns;
return;
}
if(answerString[b][e].compareTo(ns)<=0) return;
answerString[b][e]=ns;
}
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(new FileReader("ambigram.in"));
PrintWriter pw = new PrintWriter(new FileWriter("ambigram.out"));
int n;
s=sc.nextLine();
n=s.length();
for(int i=0; i<n; i++) for(int j=0; j<i; j++) {
answerInt[i][j]=0;
answerString[i][j]="";
}
for(int i=0; i<n; i++) {
answerInt[i][i]=remove(s.charAt(i));
answerString[i][i]="";
for(int j=8; j>=0; j--) if(answerInt[i][i]>=distance(s.charAt(i), first.charAt(j))) {
answerInt[i][i]=distance(s.charAt(i), first.charAt(j));
answerString[i][i]=Character.toString(first.charAt(j));
}
}
for(int l=2; l<=n; l++) for(int i=0; i+l<=n; i++) {
answerInt[i][i+l-1]=10000;
answerString[i][i+l-1]="";
bet(i, i+l-1, answerInt[i][i+l-2]+remove(s.charAt(i+l-1)), answerString[i][i+l-2]);
bet(i, i+l-1, answerInt[i+1][i+l-1]+remove(s.charAt(i)), answerString[i+1][i+l-1]);
for(int j=0; j<9; j++) {
bet(i, i+l-1, answerInt[i+1][i+l-2]+distance(s.charAt(i), first.charAt(j))+distance(s.charAt(i+l-1), next.charAt(j)), Character.toString(first.charAt(j))+answerString[i+1][i+l-2]+Character.toString(next.charAt(j)));
}
}
if(answerString[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(first.charAt(j)!=next.charAt(j)) continue;
if(distance(s.charAt(i), first.charAt(j))-remove(s.charAt(i))<c) {
c=remove(s.charAt(i))-distance(s.charAt(i), first.charAt(j));
ans=first.charAt(j);
}
if(distance(s.charAt(i), first.charAt(j))-remove(s.charAt(i))==c) {
if(ans>first.charAt(j)) ans=first.charAt(j);
}
}
pw.print(ans);
} else pw.print(answerString[0][n-1]);
pw.close();
}
}