#include <bits/stdc++.h>
using namespace std;
template <typename T>
T next_int() {
  T x = 0, p = 1;
  char ch;
  do {
    ch = getchar();
  } while (ch <= ' ');
  if (ch == '-') {
    p = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + (ch - '0');
    ch = getchar();
  }
  return p * x;
}
string next_token() {
  char ch;
  string ans = "";
  do {
    ch = getchar();
  } while (ch <= ' ');
  while (ch > ' ') {
    ans += ch;
    ch = getchar();
  }
  return ans;
}
const long long INF = (long long)1e18;
const int INFINT = (int)1e9 + 227 + 1;
const int MAXN = (int)1e6 + 227 + 1;
const int MOD = (int)1e9 + 7;
const long double EPS = 1e-9;
long long bin_pow(long long a, long long b) {
  if (!b) return 1;
  long long ans = bin_pow(a, b / 2);
  ans = ans * ans;
  if (b % 2) ans = ans * a;
  return ans;
}
string rev(string a) {
  string b = a;
  reverse((b).begin(), (b).end());
  return b;
}
bool used[MAXN];
map<string, set<pair<int, int> > > q[2];
int main() {
  int n, m;
  cin >> n >> m;
  vector<pair<int, string> > a(n);
  for (int i = 0; i < n; i++) {
    a[i].second = next_token();
    a[i].first = next_int<int>();
  }
  sort((a).begin(), (a).end());
  reverse((a).begin(), (a).end());
  string ans = "";
  long long ansi = 0;
  for (int i = 0; i < n; i++) {
    string r = rev(a[i].second);
    if (r == a[i].second) {
      q[1][a[i].second].insert(make_pair(a[i].first, i));
      continue;
    }
    if (q[0][r].size() && a[i].first + (*--q[0][r].end()).first > 0) {
      pair<int, int> f = (*--q[0][r].end());
      ansi += a[i].first;
      ansi += f.first;
      used[f.second] = 1;
      used[i] = 1;
      q[0][r].erase(f);
    } else {
      q[0][a[i].second].insert(make_pair(a[i].first, i));
    }
  }
  int temp = 0;
  long long sum = 0;
  for (map<string, set<pair<int, int> > >::iterator i = q[1].begin();
       i != q[1].end(); i++) {
    set<pair<int, int> > a = i->second;
    vector<pair<int, int> > kek;
    for (auto i : a) kek.push_back(i);
    reverse((kek).begin(), (kek).end());
    for (int i = 0; i < (int)(kek.size() / 2); i++) {
      if (!(kek[i * 2].first > 0 && kek[i * 2 + 1].first > 0)) {
        if (kek[i * 2].first + kek[i * 2 + 1].first < 0)
          temp = max(temp, kek[i * 2].first);
        else {
          ansi += kek[i * 2].first + kek[i * 2 + 1].first;
          temp = max(temp, -kek[i * 2 + 1].first);
        }
        break;
      }
      ansi += kek[i * 2].first + kek[i * 2 + 1].first;
    }
    if (kek.size() % 2 && kek.back().first > 0) {
      temp = max(temp, kek.back().first);
    }
  }
  cout << ansi + temp << "\n";
}
