#include <bits/stdc++.h>
using namespace std;
int k, n;
long long ans, maxim, suma;
map<string, int> f;
deque<pair<string, int>> box[200001], b1, b2, b;
vector<pair<int, int>> trouble;
string s;
int val;
bool comp(pair<string, int> x, pair<string, int> y) {
  return x.second > y.second;
}
int main() {
  cin >> k >> n;
  int nr = 0;
  for (int i = 1; i <= k; i++) {
    cin >> s >> val;
    string s1 = s;
    reverse(s1.begin(), s1.end());
    s1 = min(s1, s);
    if (f[s1] == 0) {
      nr++;
      f[s1] = nr;
    }
    box[f[s1]].push_back({s, val});
  }
  for (int i = 1; i <= nr; i++) {
    b = box[i];
    b1.clear();
    b2.clear();
    b1.push_back(b[0]);
    for (int j = 1; j < b.size(); j++) {
      if (b[j].first == b1[0].first)
        b1.push_back(b[j]);
      else
        b2.push_back(b[j]);
    }
    sort(b1.begin(), b1.end(), comp);
    sort(b2.begin(), b2.end(), comp);
    if (!b2.empty()) {
      while (b1.size() != b2.size()) {
        if (b1.size() > b2.size())
          b1.pop_back();
        else
          b2.pop_back();
      }
      for (int j = 0; j < b1.size(); j++)
        if (b1[j].second + b2[j].second > 0) ans += b1[j].second + b2[j].second;
    } else {
      s = b1.front().first;
      string s1 = s;
      reverse(s1.begin(), s1.end());
      if (s == s1) {
        while (b1.size() >= 2) {
          if (b1[0].second < 0 || b1[1].second < 0) break;
          ans += b1[0].second + b1[1].second;
          b1.pop_front();
          b1.pop_front();
        }
        if (b1.size() == 1 && b1[0].second > 0)
          trouble.push_back({b1[0].second, -1e8});
        if (b1.size() >= 2 && b1[0].second > 0)
          trouble.push_back({b1[0].second, b1[1].second});
      }
    }
  }
  for (auto i : trouble) {
    suma += max(i.first + i.second, 0);
    if (suma > maxim) maxim = suma;
  }
  for (auto i : trouble) {
    long long sum1 = suma - max(i.first + i.second, 0) + i.first;
    if (sum1 > maxim) maxim = sum1;
  }
  cout << ans + maxim;
  return 0;
}
