#include <bits/stdc++.h>
using namespace std;
int n, k, v, ans, big, cnt;
string s, no;
map<string, int> m;
map<string, int>::iterator it;
vector<pair<int, int> > pal;
struct nod {
  priority_queue<int> q;
  int dui;
} st[100005];
int main() {
  cin >> k >> n;
  for (int i = 1; i <= k; i++) {
    cin >> s >> v;
    if (!m.count(s)) m[s] = ++cnt;
    st[m[s]].q.push(v);
  }
  for (it = m.begin(); it != m.end(); it++) {
    string now = it->first, now2;
    for (int i = now.size() - 1; i >= 0; i--) now2 += now[i];
    if (!m.count(now2))
      st[it->second].dui = -1;
    else
      st[it->second].dui = m[now2];
  }
  for (int i = 1; i <= cnt; i++) {
    if (st[i].dui == -1) continue;
    if (st[i].dui == i) {
      if (st[i].q.empty() || st[i].q.top() <= 0) continue;
      while (!st[i].q.empty() && st[i].q.top() > 0) {
        if (st[i].q.size() == 1) {
          if (st[i].q.top() > 0) big = max(big, st[i].q.top());
          st[i].q.pop();
        } else {
          int m = st[i].q.top();
          st[i].q.pop();
          int n = st[i].q.top();
          st[i].q.pop();
          if (m > 0) {
            if (n < 0) {
              if (m + n > 0)
                pal.push_back(make_pair(m, n));
              else
                big = max(big, m);
            } else if (n >= 0)
              ans += m + n;
          }
        }
      }
    } else {
      if (st[i].q.empty()) continue;
      while (!st[i].q.empty() && !st[st[i].dui].q.empty()) {
        int m = st[i].q.top();
        st[i].q.pop();
        int n = st[st[i].dui].q.top();
        st[st[i].dui].q.pop();
        if (m + n <= 0)
          break;
        else if (m + n > 0)
          ans += m + n;
      }
    }
  }
  int sum = 0;
  for (int i = 0; i < pal.size(); i++) sum += pal[i].first + pal[i].second;
  int u = sum + big;
  for (int i = 0; i < pal.size(); i++)
    if (pal[i].first > big) u = max(u, sum - pal[i].second);
  ans += u;
  cout << ans << endl;
  return 0;
}
