#include <bits/stdc++.h>
using namespace std;
vector<pair<string, long long> > a, b;
map<string, vector<long long> > mp;
bool check(string &s) {
  for (long long i = 0; i < s.length() / 2; ++i)
    if (s[i] != s[s.length() - i - 1]) return 0;
  return 1;
}
int main() {
  long long n, k;
  cin >> k >> n;
  string s, rev;
  long long c;
  for (long long i = 0; i < k; ++i) {
    cin >> s >> c;
    if (check(s))
      mp[s].push_back(c);
    else {
      rev = "";
      for (long long j = n - 1; j >= 0; --j) rev += s[j];
      a.push_back({s, -c});
      b.push_back({rev, -c});
    }
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  long long l = 0, r = 0, ans = 0;
  for (long long l = 0; l < a.size() && r < b.size(); ++l) {
    while (a[l].first > b[r].first && r < b.size() - 1) {
      r++;
    }
    if (a[l].first == b[r].first) {
      if (-(a[l].second + b[r].second) > 0) {
        ans += -(a[l].second + b[r].second);
        r++;
      }
    }
  }
  ans /= 2;
  long long mx = 0, mx2 = 0;
  for (auto it = mp.begin(); it != mp.end(); ++it) {
    vector<long long> &v = it->second;
    sort(v.rbegin(), v.rend());
    for (long long i = 1; i < v.size(); i += 2) {
      if (v[i] + v[i - 1] > 0)
        ans += v[i] + v[i - 1];
      else {
        if (v[i - 1] > mx) mx = v[i - 1];
        break;
      }
      if (v[i] < 0) mx2 = max(mx2, -v[i]);
    }
    if (v.size() & 1) {
      if (v[v.size() - 1] > mx) mx = v[v.size() - 1];
    }
  }
  cout << max(ans + mx, ans + mx2);
  return 0;
}
