#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, k;
  cin >> k >> n;
  vector<pair<string, int>> pal, nor, rev;
  for (int i = 0; i < k; i++) {
    string s;
    int val;
    cin >> s >> val;
    string t = s;
    reverse(t.begin(), t.end());
    if (s == t)
      pal.push_back({s, val});
    else {
      nor.push_back({s, val});
      rev.push_back({t, val});
    }
  }
  sort(pal.begin(), pal.end());
  sort(nor.begin(), nor.end());
  sort(rev.begin(), rev.end());
  int answer = 0;
  while (!nor.empty() && !rev.empty()) {
    if (nor.back().first == rev.back().first) {
      int temp = nor.back().second + rev.back().second;
      answer += max(temp, 0);
      nor.pop_back();
      rev.pop_back();
    } else if (nor.back().first > rev.back().first)
      nor.pop_back();
    else
      rev.pop_back();
  }
  answer /= 2;
  int greatest = 0;
  int smallest = 0;
  string prev;
  int val = 0;
  while (!pal.empty()) {
    if (prev == pal.back().first) {
      int temp = pal.back().second;
      if (val + temp > 0) {
        answer += val + temp;
        smallest = min({smallest, temp});
      } else {
        greatest = max(greatest, val);
      }
      prev.erase();
      val = 0;
    } else {
      greatest = max(greatest, val);
      prev = pal.back().first;
      val = pal.back().second;
    }
    pal.pop_back();
  }
  answer += max({greatest, -smallest, val});
  cout << answer << endl;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
