#include <bits/stdc++.h>
using namespace std;
template <class T>
bool setmax(T &_a, T _b) {
  if (_a < _b) {
    _a = _b;
    return true;
  }
  return false;
}
inline void Boost() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
}
int main() {
  int n, k;
  cin >> n >> k;
  map<string, pair<vector<int>, vector<int> > > m1;
  map<string, vector<int> > m2;
  for (int i = 0; i < n; i++) {
    string s, rs;
    int val;
    cin >> s >> val;
    rs = s;
    reverse(rs.begin(), rs.end());
    if (s == rs) {
      auto it = m2.find(s);
      if (it == m2.end())
        m2.insert({s, {val}});
      else
        it->second.push_back(val);
    } else {
      auto it = m1.find(s);
      if (it != m1.end()) {
        it->second.first.push_back(val);
      } else {
        it = m1.find(rs);
        if (it != m1.end())
          it->second.second.push_back(val);
        else
          m1.insert({s, {{val}, {}}});
      }
    }
  }
  int ans = 0, bonus = 0;
  for (auto &it : m1) {
    auto &v1 = it.second.first;
    auto &v2 = it.second.second;
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    while (!v1.empty() && !v2.empty()) {
      int cur = v1.back() + v2.back();
      if (cur < 0) break;
      ans += cur;
      v1.pop_back();
      v2.pop_back();
    }
  }
  for (auto &it : m2) {
    auto &v = it.second;
    sort(v.begin(), v.end());
    while (v.size() >= 2 && v[v.size() - 2] > 0) {
      ans += v[v.size() - 2] + v[v.size() - 1];
      v.pop_back();
      v.pop_back();
    }
    if (v.size() >= 2 && v[v.size() - 2] + v[v.size() - 1] > 0) {
      assert(v[v.size() - 2] <= 0);
      ans += v[v.size() - 2] + v[v.size() - 1];
      setmax(bonus, -v[v.size() - 2]);
    } else if (v.size() >= 1 && v.back() > 0)
      setmax(bonus, v.back());
  }
  cout << ans + bonus;
  return 0;
}
