#include <bits/stdc++.h>
using namespace std;
int n, k, answ, sum;
map<string, int> m;
vector<vector<int>> g[2];
vector<int> a;
int ma;
bool isPal(const string &s) {
  bool ok = true;
  for (register int i = 0; i < s.length(); ++i)
    ok = ok && s[i] == s[s.length() - 1 - i];
  return ok;
}
int main(void) {
  scanf("%d %d", &k, &n);
  string s;
  int x;
  while (k--) {
    cin >> s >> x;
    if (m.count(s)) {
      int i = m[s];
      g[0][i].push_back(x);
    } else {
      reverse(s.begin(), s.end());
      if (m.count(s)) {
        int i = m[s];
        g[1][i].push_back(x);
      } else {
        reverse(s.begin(), s.end());
        m[s] = g[0].size();
        g[0].push_back(vector<int>());
        g[1].push_back(vector<int>());
        g[0][g[0].size() - 1].push_back(x);
      }
    }
  }
  for (register int i = 0; i < 2; ++i)
    for (register int j = 0; j < g[i].size(); ++j)
      sort(g[i][j].begin(), g[i][j].end(), greater<int>());
  a.resize(g[0].size());
  for (auto p : m) {
    p.second;
    if (isPal(p.first)) {
      x = 0;
      for (int j = 2; j <= g[0][p.second].size(); j += 2)
        x += max(0, g[0][p.second][j - 1] + g[0][p.second][j - 2]);
      int y = 0;
      for (int j = 0; j < g[0][p.second].size() && g[0][p.second][j] > 0; ++j)
        y += g[0][p.second][j];
      a[p.second] = y - x;
      ma = max(ma, y - x);
      sum += x;
    } else {
      x = 0;
      int ln = min(g[0][p.second].size(), g[1][p.second].size());
      for (int j = 0; j < ln; ++j)
        x += max(0, g[0][p.second][j] + g[1][p.second][j]);
      a[p.second] = 0;
      sum += x;
    }
  }
  printf("%d\n", sum + ma);
  return 0;
}
