#include <bits/stdc++.h>
using namespace std;
string complement(string s) {
  string res = s;
  reverse(res.begin(), res.end());
  return res;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long k, n;
  cin >> k >> n;
  map<string, vector<long long> > mp;
  map<string, bool> been;
  for (long long i = 0; i <= k - 1; ++i) {
    string s;
    long long a;
    cin >> s >> a;
    mp[s].push_back(a);
  }
  long long ans = 0, mi = 0;
  for (pair<string, vector<long long> > p : mp) {
    string s = p.first, s2 = complement(s);
    vector<long long> vals = mp[s], vals2 = mp[s2];
    sort(vals.begin(), vals.end()), sort(vals2.begin(), vals2.end());
    if (been[s]) continue;
    been[s2] = 1;
    if (s == s2) {
      while (vals.size() > 1) {
        long long a = vals.back();
        vals.pop_back();
        long long b = vals.back();
        vals.pop_back();
        if (a + b > 0) {
          ans += a + b;
          if (min(a, b) < 0) mi = min(mi, min(a, b));
        } else {
          if (max(a, b) > 0) mi = min(mi, -max(a, b));
          break;
        }
      }
      if (vals.size() == 1) mi = min(mi, -vals.back());
      continue;
    }
    while (!vals.empty() && !vals2.empty() && vals.back() + vals2.back() > 0) {
      ans += vals.back() + vals2.back();
      vals.pop_back(), vals2.pop_back();
    }
  }
  cout << ans - mi << "\n";
  return 0;
}
