#include <bits/stdc++.h>
using namespace std;
long long x, y, z, a, b, c, ans;
map<string, priority_queue<long long>> p;
set<string> st;
string s, ss;
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  ;
  cin >> x >> y;
  for (int i = 0; i < x; i++) {
    cin >> s >> a;
    st.insert(s);
    p[s].push(a);
  }
  for (auto i : st) {
    ss = i;
    reverse(ss.begin(), ss.end());
    if (p[ss].size() > 0) {
      if (ss == i) {
        while (p[ss].size() > 0) {
          if (p[ss].size() == 1) {
            c = max(p[ss].top(), c);
            p[ss].pop();
            break;
          }
          a = p[ss].top(), p[ss].pop(), b = p[ss].top(), p[ss].pop();
          if ((a + b) >= 0) {
            ans += (a + b);
            c = max(c, -b);
          } else {
            c = max({c, a, b});
            break;
          }
        }
      } else {
        while (p[ss].size() > 0 && p[i].size() > 0 &&
               (p[i].top() + p[ss].top()) > 0) {
          ans += (p[i].top() + p[ss].top());
          p[ss].pop();
          p[i].pop();
        }
      }
    }
  }
  cout << c + ans << endl;
  return 0;
}
