#include <bits/stdc++.h>
using namespace std;
const int INF = 987654321;
bool isSelfPalin(const string& str) {
  int n = str.size();
  for (int i = 0; i < n / 2; ++i) {
    int back = n - 1 - i;
    if (str[i] != str[back]) return false;
  }
  return true;
}
int main() {
  ios::sync_with_stdio(false);
  int k, n;
  cin >> k >> n;
  map<string, multiset<int>> org_word;
  map<string, multiset<int>> rev_word;
  map<string, multiset<int>> self_palin;
  for (int i = 0; i < (k); ++i) {
    string str;
    int ai;
    cin >> str >> ai;
    if (isSelfPalin(str))
      self_palin[str].insert(ai);
    else {
      if (org_word.count(str) > 0)
        org_word[str].insert(ai);
      else if (rev_word.count(str) > 0)
        rev_word[str].insert(ai);
      else {
        org_word[str].insert(ai);
        string rev = str;
        reverse(rev.begin(), rev.end());
        rev_word[rev] = multiset<int>();
      }
    }
  }
  long long sol = 0;
  map<string, multiset<int>>::iterator it = org_word.begin();
  for (; it != org_word.end(); ++it) {
    string orgKey = it->first;
    string revKey = orgKey;
    reverse(revKey.begin(), revKey.end());
    multiset<int>::reverse_iterator jt1 = org_word[orgKey].rbegin();
    multiset<int>::reverse_iterator jt2 = rev_word[revKey].rbegin();
    while (jt1 != org_word[orgKey].rend() && jt2 != rev_word[revKey].rend()) {
      if ((*jt1 + *jt2) < 0) break;
      sol += (*jt1 + *jt2);
      ++jt1;
      ++jt2;
    }
  }
  vector<pair<int, int>> tmp;
  it = self_palin.begin();
  for (; it != self_palin.end(); ++it) {
    multiset<int>::reverse_iterator jt = it->second.rbegin();
    bool zero = true;
    int prv = 0;
    while (jt != it->second.rend()) {
      if (*jt < 0) break;
      if (zero) {
        prv = *jt;
        zero = false;
      } else {
        sol += (prv + *jt);
        zero = true;
      }
      ++jt;
    }
    if (zero == false) {
      if (jt == it->second.rend())
        tmp.push_back(make_pair(prv, -INF));
      else
        tmp.push_back(make_pair(prv, *jt));
    }
  }
  long long cand = 0;
  for (int i = 0; i < (tmp.size()); ++i) {
    if ((tmp[i].first + tmp[i].second) > 0) {
      cand += (tmp[i].first + tmp[i].second);
    }
  }
  long long add = cand;
  for (int i = 0; i < (tmp.size()); ++i) {
    if (tmp[i].second == -INF) {
      if (add < cand + tmp[i].first) add = cand + tmp[i].first;
    } else if ((tmp[i].first + tmp[i].second) <= 0) {
      if (add < cand + tmp[i].first) add = cand + tmp[i].first;
    } else {
      if (add < cand - tmp[i].second) add = cand - tmp[i].second;
    }
  }
  sol = sol + add;
  cout << sol;
  return 0;
}
