#include <bits/stdc++.h>
using namespace std;
map<string, vector<long long> > mp;
int n, k;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  string s;
  long long x;
  cin >> k >> n;
  for (int i = (int)0; i < (int)k; ++i) {
    cin >> s >> x;
    mp[s].push_back(x);
  }
  long long ans = 0, res = 0, mid = 0;
  for (auto& p : mp) {
    auto& s = p.first;
    auto& v = p.second;
    sort(v.begin(), v.end());
    reverse(v.begin(), v.end());
    auto r = s;
    reverse(r.begin(), r.end());
    if (r == s) {
      int i = 0;
      for (; i < ((int)(v).size()) - 1; i += 2) {
        if (v[i] + v[i + 1] < 0) break;
        ans += v[i] + v[i + 1];
        mid = max(mid, -v[i + 1]);
      }
      for (; i < ((int)(v).size()); ++i) mid = max(mid, v[i]);
    } else {
      if (mp[r].empty()) continue;
      auto& vr = mp[r];
      sort(vr.begin(), vr.end());
      reverse(vr.begin(), vr.end());
      int x = min(((int)(vr).size()), ((int)(v).size()));
      for (int i = 0; i < x; ++i) {
        if (v[i] + vr[i] <= 0) break;
        res += v[i] + vr[i];
      }
    }
  }
  cout << (ans + mid + res / 2) << endl;
  return 0;
}
