#include <bits/stdc++.h>
using namespace std;
ifstream fin("f.in");
ofstream fout("f.out");
map<string, vector<int> > mp;
bool isPal(string s) {
  int len = s.size();
  for (int i = 0; i <= len - 1; ++i) {
    if (s[i] != s[len - 1 - i]) {
      return false;
    }
  }
  return true;
}
bool isLessThanRev(string s) {
  int len = s.size();
  for (int i = 0; i <= len - 1; ++i) {
    if (s[i] != s[len - 1 - i]) {
      if (s[i] < s[len - 1 - i]) {
        return true;
      } else {
        return false;
      }
    }
  }
}
int getSide(string s) {
  vector<int> v1, v2;
  for (auto i : mp[s]) v1.push_back(i);
  reverse(s.begin(), s.end());
  for (auto i : mp[s]) v2.push_back(i);
  sort(v1.rbegin(), v1.rend());
  sort(v2.rbegin(), v2.rend());
  while (v1.size() > v2.size()) v1.pop_back();
  while (v2.size() > v1.size()) v2.pop_back();
  while (!v1.empty() && v1.back() + v2.back() < 0) {
    v1.pop_back();
    v2.pop_back();
  }
  int ret = 0;
  for (auto x : v1) ret += x;
  for (auto x : v2) ret += x;
  return ret;
}
int getMid(string s, bool isMid = false) {
  vector<int> v;
  for (auto i : mp[s]) v.push_back(i);
  sort(v.rbegin(), v.rend());
  int len = v.size();
  int cur = 0;
  int ret = 0;
  for (int i = 0; i <= len - 1; ++i) {
    cur += v[i];
    if ((isMid && i % 2 == 0) || (!isMid && i & 1)) {
      ret = (ret > cur) ? ret : cur;
    }
  }
  return ret;
}
void solve() {
  int k, n;
  cin >> k >> n;
  string s;
  int a;
  for (int i = 1; i <= k; ++i) {
    cin >> s >> a;
    mp[s].push_back(a);
  }
  int ans = 0;
  for (auto i : mp) {
    if (isPal(i.first)) {
      ans += getMid(i.first);
    } else if (isLessThanRev(i.first)) {
      ans += getSide(i.first);
    }
  }
  int maxMid = 0;
  for (auto i : mp) {
    if (isPal(i.first)) {
      int tmp = getMid(i.first, true) - getMid(i.first);
      maxMid = (maxMid >= tmp) ? maxMid : tmp;
    }
  }
  ans += maxMid;
  cout << ans << endl;
}
int main(int argc, char const *argv[]) {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  solve();
  return 0;
}
