#include <bits/stdc++.h>
using namespace std;
const int sz = 1e5;
int n, k;
map<string, vector<int>> mem;
vector<vector<int>> palis;
bool isPali(string s) {
  for (int i = 0; i < k >> 1; i++) {
    if (s[i] != s[k - i - 1]) return 0;
  }
  return 1;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    string s;
    int a;
    cin >> s >> a;
    if (mem.find(s) == mem.end())
      mem[s] = {a};
    else
      mem[s].push_back(a);
  }
  long long tot = 0;
  while (!mem.empty()) {
    auto x = mem.begin();
    sort(x->second.rbegin(), x->second.rend());
    if (isPali(x->first)) {
      palis.push_back(x->second);
    } else {
      string rev = x->first;
      reverse(rev.begin(), rev.end());
      if (mem.find(rev) != mem.end()) {
        vector<int> v = mem[rev];
        sort(v.rbegin(), v.rend());
        mem.erase(rev);
        int i = 0;
        while (i < v.size() && i < x->second.size()) {
          if (v[i] + x->second[i] > 0)
            tot += (v[i] + x->second[i]);
          else
            break;
          i++;
        }
      }
    }
    mem.erase(x);
  }
  int paliSize = palis.size();
  vector<int> reg(paliSize, 0);
  long long treg = 0;
  for (int i = 0; i < paliSize; i++) {
    int j = 0;
    while (j + 1 < palis[i].size() and palis[i][j] + palis[i][j + 1] > 0) {
      reg[i] += palis[i][j] + palis[i][j + 1];
      j += 2;
    }
    treg += reg[i];
  }
  long long bst = treg;
  for (int i = 0; i < paliSize; i++) {
    long long cr = treg - reg[i] + palis[i][0];
    int j = 1;
    while (j + 1 < palis[i].size() and palis[i][j] + palis[i][j + 1] > 0) {
      cr += palis[i][j] + palis[i][j + 1];
      j += 2;
    }
    bst = max(bst, cr);
  }
  cout << tot + bst << '\n';
  return 0;
}
