#include <bits/stdc++.h>
using namespace std;
bool is_pal(string a) {
  for (int i = 0; 2 * i < a.size(); i++) {
    if (a[i] != a[a.size() - i - 1]) return 0;
  }
  return 1;
}
string rev(string s) {
  reverse(s.begin(), s.end());
  return s;
}
unordered_map<string, vector<int>> hm;
unordered_map<string, int> hm_cnt;
vector<string> v;
int main() {
  int n;
  cin >> n;
  int sz;
  cin >> sz;
  for (int i = 0; i < n; i++) {
    string s;
    int beauty;
    cin >> s >> beauty;
    hm[s].push_back(beauty);
    hm_cnt[s] += 1;
  }
  int sum = 0;
  for (auto it : hm) {
    string s = it.first;
    sort(hm[s].begin(), hm[s].end());
    reverse(hm[s].begin(), hm[s].end());
    sort(hm[rev(s)].begin(), hm[rev(s)].end());
    reverse(hm[rev(s)].begin(), hm[rev(s)].end());
    vector<int> v1 = hm[s];
    vector<int> v2 = hm[rev(s)];
    if (s != rev(s)) {
      for (int i = 0; i < v1.size() && i < v2.size() && v1[i] + v2[i] > 0;
           i++) {
        sum += v1[i] + v2[i];
        hm_cnt[s] -= 1;
      }
    } else {
      for (int i = 0;
           i < v1.size() && i + 1 < v2.size() && v1[i] + v2[i + 1] > 0;
           i += 2) {
        sum += 2 * (v1[i] + v2[i + 1]);
        hm_cnt[s] -= 2;
      }
    }
  }
  sum /= 2;
  int maxim = -123456;
  for (auto it : hm_cnt) {
    if (is_pal(it.first) && it.second > 0) {
      maxim = max(maxim, hm[it.first][hm[it.first].size() - it.second]);
    }
  }
  int minim = 123456;
  for (auto it : hm_cnt) {
    if (is_pal(it.first) && it.second < hm[it.first].size()) {
      minim = min(minim, hm[it.first][hm[it.first].size() - it.second - 1]);
    }
  }
  maxim = max(maxim, -minim);
  if (maxim > 0) sum += maxim;
  cout << sum;
}
