W
H
X

longpo的回文



#include <bits/stdc++.h>
using namespace std;
const int N = 55;
#define ll long long
char c[N], o[N], a[N], b[N];
int n, m, val; ll d[N][N], f[N][N];
#define chk(a, b) (a = a > b ? b : a)
signed main() {
    scanf ("%s %d", c + 1, &m);
    n = strlen (c + 1);
    memset (d, 0x1f, sizeof (d));
    for (int i = 0; i <= 26; ++i) d[i][i] = 0;
    for (int i = 1; i <= m; ++i) {
        scanf ("%s", o);
        if (o[0] == 'e') {
            scanf ("%s %d", a, &val);
            chk (d[a[0] - 'a' + 1][0], val);
        } else if (o[0] == 'a') {
            scanf ("%s %d", a, &val);
            chk (d[0][a[0] - 'a' + 1], val);
        } else {
            scanf ("%s %s %d", a, b, &val);
            chk (d[a[0] - 'a' + 1][b[0] - 'a' + 1], val);
        }
    }
    for (int k = 0; k <= 26; ++k)
        for (int i = 0; i <= 26; ++i)
            for (int j = 0; j <= 26; ++j)
                chk (d[i][j], d[i][k] + d[k][j]);
    memset (f, 0x1f, sizeof (f)); ll inf = f[0][0];
    for (int i = 1; i <= n; ++i) f[i][i] = f[i][i - 1] = 0;
    for (int i = 1; i <= n; ++i) c[i] = c[i] - 'a' + 1;
    for (int len = 2; len <= n; ++len) {
        for (int l = 1; l + len - 1 <= n; ++l) {
            int r = l + len - 1;
            if (c[l] == c[r]) f[l][r] = f[l + 1][r - 1];
            for (int k = 0; k <= 26; ++k) {
                chk (f[l][r], f[l + 1][r] + d[c[l]][k] + d[0][k]);
                chk (f[l][r], f[l][r - 1] + d[c[r]][k] + d[0][k]);
                chk (f[l][r], f[l + 1][r - 1] + d[c[r]][k] + d[c[l]][k]);
            }
        }
    } if (f[1][n] >= inf) f[1][n] = -1;
    return printf ("%lld\n", f[1][n]), 0;
}
posted @ 2020-07-24 00:43  -敲键盘的猫-  阅读(140)  评论(0编辑  收藏  举报