#include <bits/stdc++.h>
using namespace std;
set<string> picked;
map<string, vector<long long int>> pal;
map<string, vector<long long int>> notPal;
int k, n;
bool isPal(string s) {
  string rs = s;
  reverse(rs.begin(), rs.end());
  if (rs.compare(s) == 0) return true;
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> k >> n;
  for (int i = 0; i < k; i++) {
    string s;
    cin >> s;
    long long int c;
    cin >> c;
    if (isPal(s)) {
      pal[s].push_back(c);
    } else {
      notPal[s].push_back(c);
    }
  }
  long long int tot = 0;
  for (auto p : notPal) {
    if (picked.count(p.first) > 0) continue;
    string rs = p.first;
    reverse(rs.begin(), rs.end());
    picked.insert(p.first);
    picked.insert(rs);
    if (notPal.find(rs) != notPal.end()) {
      vector<long long int> l1 = p.second;
      auto it = notPal.find(rs);
      vector<long long int> l2 = it->second;
      sort(begin(l1), end(l1), greater<long long int>());
      sort(begin(l2), end(l2), greater<long long int>());
      for (int i = 0; i < min(l1.size(), l2.size()); i++) {
        long long int cost = l1[i] + l2[i];
        if (cost > 0) {
          tot += cost;
        } else {
          break;
        }
      }
    }
  }
  long long int maxi = -1e9;
  for (auto p : pal) {
    vector<long long int> vec = p.second;
    sort(vec.begin(), vec.end(), greater<long long int>());
    int i = 0;
    if (vec.size() == 1 && vec[0] > 0) {
      maxi = max(maxi, vec[0]);
    } else {
      vector<pair<long long int, long long int>> pairs;
      for (; i < vec.size() - 1; i += 2) {
        long long int cost = vec[i] + vec[i + 1];
        if (cost >= 0) {
          tot += cost;
          pairs.push_back({vec[i], vec[i + 1]});
        } else {
          break;
        }
      }
      if (i >= vec.size()) {
        int ind = vec.size() - 1;
        if (vec.size() % 2 != 0 && vec[ind] > 0) {
          maxi = max(maxi, llabs(vec[ind]));
        } else if (pairs.size() > 0) {
          pair<long long int, long long int> pa = pairs[pairs.size() - 1];
          long long int a = pa.first;
          long long int b = pa.second;
          if (a < b) swap(a, b);
          if (b < 0) maxi = max(maxi, llabs(b));
        }
      } else {
        if (vec[i] > 0) {
          maxi = max(maxi, llabs(vec[i]));
        } else if (pairs.size() > 0) {
          pair<long long int, long long int> pa = pairs[pairs.size() - 1];
          long long int a = pa.first;
          long long int b = pa.second;
          if (a < b) swap(a, b);
          if (b < 0) maxi = max(maxi, llabs(b));
        }
      }
    }
  }
  if (maxi > 0) {
    tot += maxi;
  }
  cout << tot << '\n';
  return 0;
}
