#include <bits/stdc++.h>
using namespace std;
const int UNDEF = -1;
const int INF = 2e9;
template <typename T>
inline bool chkmax(T &aa, T bb) {
  return aa < bb ? aa = bb, true : false;
}
template <typename T>
inline bool chkmin(T &aa, T bb) {
  return aa > bb ? aa = bb, true : false;
}
template <class T>
T extgcd(T a, T b, T &x, T &y) {
  for (T u = y = 1, v = x = 0; a;) {
    T q = b / a;
    swap(x -= q * u, u);
    swap(y -= q * v, v);
    swap(b -= q * a, a);
  }
  return b;
}
template <class T>
T mod_inv(T a, T m) {
  T x, y;
  extgcd(a, m, x, y);
  return (m + x % m) % m;
}
map<string, pair<vector<int>, vector<int> > > h;
map<string, vector<int> > g;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int k, n;
  cin >> k >> n;
  for (int i = 0; i < k; i++) {
    string s;
    int a;
    cin >> s >> a;
    string r = s;
    reverse(r.begin(), r.end());
    if (s < r) {
      h[s].first.push_back(a);
    } else if (s > r) {
      h[r].second.push_back(a);
    } else
      g[s].push_back(a);
  }
  int final = 0;
  for (auto &ww : h) {
    auto &w = ww.second;
    sort(w.first.begin(), w.first.end(), greater<int>());
    sort(w.second.begin(), w.second.end(), greater<int>());
    int sz = min(w.first.size(), w.second.size());
    for (int i = 0; i < sz; i++) {
      int cand = w.first[i] + w.second[i];
      if (cand > 0) final += cand;
    }
  }
  int woof = 0;
  int best = 0;
  for (auto &w : g) {
    sort(w.second.begin(), w.second.end(), greater<int>());
    int sz = w.second.size();
    if (sz == 0) continue;
    int c0 = 0;
    for (int i = 0; i + 1 < sz; i += 2) {
      int cand = w.second[i] + w.second[i + 1];
      if (cand > 0) c0 += cand;
    }
    woof += c0;
    int c1 = max(0, w.second[0]);
    for (int i = 1; i + 1 < sz; i += 2) {
      int cand = w.second[i] + w.second[i + 1];
      if (cand > 0) c1 += cand;
    }
    chkmax(best, c1 - c0);
  }
  int toadd = woof + best;
  final += toadd;
  printf("%d\n", final);
}
