#include <bits/stdc++.h>
using namespace std;
int n, k, rez, id;
map<string, priority_queue<int> > str;
void printStruct(map<string, priority_queue<int> > el) {
  for (auto x : el) {
    cout << "\t" << x.first << ": ";
    while (!x.second.empty()) {
      cout << x.second.top() << " ";
      x.second.pop();
    }
    cout << endl;
  }
  cout << endl;
}
int findmax(int a, int b) { return a > b ? a : b; }
int findmin(int a, int b) { return a < b ? a : b; }
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    string s;
    int tmp;
    cin >> s >> tmp;
    str[s].push(tmp);
  }
  int minTaken = 0x0FFFFFFF;
  for (auto &el : str) {
    string rev = el.first;
    reverse(rev.begin(), rev.end());
    if (rev > el.first) continue;
    if (rev == el.first) {
      while (el.second.size() >= 2) {
        int beauty1 = el.second.top();
        el.second.pop();
        int beauty2 = el.second.top();
        el.second.pop();
        if (beauty2 + beauty1 >= 0) {
          rez += beauty1 + beauty2;
          minTaken = findmin(beauty1, minTaken);
          minTaken = findmin(beauty2, minTaken);
        } else {
          el.second.push(beauty1);
          el.second.push(beauty2);
          break;
        }
      }
    } else {
      auto &elRev = str[rev];
      while (!el.second.empty() && !elRev.empty() &&
             elRev.top() + el.second.top() >= 0) {
        int beauty1 = el.second.top();
        el.second.pop();
        int beauty2 = elRev.top();
        elRev.pop();
        rez += beauty1 + beauty2;
      }
    }
  }
  int max = 0;
  if (minTaken < 0) max = -1 * minTaken;
  for (auto &el : str) {
    string rev = el.first;
    reverse(rev.begin(), rev.end());
    if (rev == el.first && !el.second.empty()) {
      max = findmax(max, el.second.top());
    }
  }
  rez += max;
  cout << rez << endl;
  cout << endl;
  return 0;
}
