#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10, inf = 1e9 + 10, P = 769, MOD = 1e9 + 7;
map<long long, vector<long long> > m;
map<long long, bool> q;
map<long long, long long> m2;
long long p[maxn];
char c[maxn];
vector<long long> v;
vector<long long> mx;
long long Hash1(string s) {
  long long k = 0;
  for (int i = 0; i < s.length(); i++) (k = (k * P + s[i])) %= MOD;
  return k;
}
long long Hash2(string s) {
  long long k = 0;
  for (int i = s.length() - 1; i >= 0; i--) (k = (k * P + s[i])) %= MOD;
  return k;
}
int main() {
  long long ans = 0;
  p[0] = 1;
  for (int i = 0; i < maxn; i++) (p[i] = p[i - 1] * P) %= MOD;
  string s;
  int n, k;
  scanf("%d%d", &n, &k);
  for (int i = 0, x; i < n; i++) {
    s = "";
    scanf("%s%d", &c, &x);
    for (int j = 0; j < k; j++) s += c[j];
    long long t = Hash1(s);
    m2[t] = Hash2(s);
    if (!m[t].size()) v.push_back(t);
    m[t].push_back(x);
  }
  for (int i = 0; i < v.size(); i++) {
    if (q[v[i]] || q[m2[v[i]]]) continue;
    q[v[i]] = true;
    q[m2[v[i]]] = true;
    sort(m[v[i]].rbegin(), m[v[i]].rend());
    sort(m[m2[v[i]]].rbegin(), m[m2[v[i]]].rend());
    int a = m[v[i]].size(), b = m[m2[v[i]]].size();
    if (v[i] == m2[v[i]])
      for (int j = 0; j < a; j++) {
        if (m[v[i]][j] < 0) break;
        if (j + 1 < a) {
          if (m[v[i]][j + 1] >= 0)
            ans += m[v[i]][j] + m[v[i]][j + 1], j++;
          else if (m[v[i]][j] + m[v[i]][j + 1] > 0) {
            mx.push_back(-m[v[i]][j + 1]);
            ans += m[v[i]][j] + m[v[i]][j + 1];
            break;
          } else
            mx.push_back(m[v[i]][j]);
        } else if (m[v[i]][j] > 0)
          mx.push_back(m[v[i]][j]);
      }
    else
      for (int j = 0; j < min(a, b); j++)
        if (m[v[i]][j] + m[m2[v[i]]][j] > 0) ans += m[v[i]][j] + m[m2[v[i]]][j];
  }
  sort(mx.rbegin(), mx.rend());
  if (mx.size() > 0) ans += mx[0];
  printf("%lld", ans);
  return 0;
}
