#include <bits/stdc++.h>
using namespace std;
map<string, long long int> vis;
map<string, long long int> has;
vector<string> vv;
long long int p[1000009];
vector<long long int> v[1000006];
long long int ck(string s) {
  long long int i, j;
  i = 0;
  j = s.length() - 1;
  while (i <= j) {
    if (s[i] != s[j]) return 0;
    i++;
    j--;
  }
  return 1;
}
int main() {
  long long int i, j, k, q, m, sum, t, n, ans;
  string s;
  cin >> n >> k;
  char ch[1000006];
  t = 1;
  for (i = 1; i <= n; i++) {
    scanf("%s", ch);
    s = ch;
    cin >> q;
    if (vis[s] == 0) {
      vis[s] = 1;
      vv.push_back(s);
      has[s] = t;
      t++;
      v[t - 1].push_back(q);
    } else {
      long long int g = has[s];
      v[g].push_back(q);
    }
  }
  for (i = 0; i <= 1000002; i++) {
    v[i].push_back(-1000000);
    v[i].push_back(-1000000);
  }
  for (i = 0; i <= 1000002; i++) {
    sort(v[i].begin(), v[i].end());
  }
  for (i = 0; i <= 1000002; i++) {
    p[i] = v[i].size() - 1;
  }
  sum = 0;
  ans = 0;
  string x, y;
  for (i = 0; i < vv.size(); i++) {
    x = vv[i];
    char tt[1000009];
    j = 0;
    long long int u;
    for (u = x.length() - 1; u >= 0; u--, j++) {
      tt[j] = x[u];
    }
    tt[j] = '\0';
    y = tt;
    long long int a, b, w, e;
    a = has[x];
    b = has[y];
    w = v[a][p[a]];
    p[a]--;
    e = v[b][p[b]];
    p[b]--;
    long long int temp = w + e;
    while (temp > 0) {
      sum += temp;
      if (w < 0) {
        long long int yy = ck(y);
        if (yy == 1) ans = min(w, e) < min(e, ans) ? min(w, e) : min(e, ans);
      } else if (e < 0) {
        long long int yy = ck(x);
        if (yy == 1) ans = min(w, e) < min(e, ans) ? min(w, e) : min(e, ans);
      }
      w = v[a][p[a]];
      p[a]--;
      e = v[b][p[b]];
      p[b]--;
      temp = w + e;
    }
    p[a]++;
    p[b]++;
  }
  m = 0;
  for (i = 0; i < vv.size(); i++) {
    s = vv[i];
    if (ck(s) == 0) continue;
    long long int qq = has[s];
    m = max(m, v[qq][p[qq]]);
  }
  m = max(m, abs(ans));
  sum += m;
  cout << sum;
}
