#include <bits/stdc++.h>
using namespace std;
int main() {
  map<string, multiset<int>> mp;
  int k, n;
  cin >> k >> n;
  set<string> st;
  for (int i = 0; i < k; ++i) {
    string s;
    int num;
    cin >> s >> num;
    string temp = s;
    reverse(s.begin(), s.end());
    if (temp < s)
      st.insert(temp);
    else
      st.insert(s);
    mp[s].insert(num);
  }
  int sum = 0;
  int mn = 0;
  for (auto it = st.begin(); it != st.end(); ++it) {
    string s = *it;
    string temp = s;
    reverse(temp.begin(), temp.end());
    if (s != temp) {
      for (auto it1 = mp[s].rbegin(), it2 = mp[temp].rbegin();
           it1 != mp[s].rend() && it2 != mp[temp].rend(); ++it1, ++it2)
        if (*it1 + *it2 > 0)
          sum += *it1 + *it2;
        else
          break;
    } else {
      for (auto it1 = mp[s].rbegin(); it1 != mp[s].rend(); it1++) {
        int num = *it1;
        it1++;
        if (it1 != mp[s].rend()) {
          if (num >= 0 && *it1 >= 0)
            sum += num + *it1;
          else if (num >= 0 && *it1 < 0) {
            if (num + *it1 >= 0) {
              mn = max(mn, -*it1);
              sum += num + *it1;
            } else
              mn = max(num, mn);
            break;
          } else
            break;
        } else {
          if (num > 0) mn = max(mn, num);
          break;
        }
      }
    }
  }
  cout << sum + mn;
  return 0;
}
