#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int n, k;
map<string, map<int, int> > dict;
char s[maxn];
bool is_reverse(const string &t) {
  for (int i = 0; i < t.size() / 2; ++i) {
    if (t[i] != t[t.size() - i - 1]) return false;
  }
  return true;
}
string rev(string t) {
  for (int i = 0; i < t.size() / 2; ++i) {
    swap(t[i], t[t.size() - 1 - i]);
  }
  return t;
}
int main() {
  scanf("%d%d", &k, &n);
  for (int i = 0; i < k; ++i) {
    int x;
    scanf("%s%d", s, &x);
    string tmp = s;
    if (dict.count(tmp)) {
      if (dict[tmp].count(x)) {
        ++dict[tmp][x];
      } else {
        dict[tmp][x] = 1;
      }
    } else {
      dict[tmp][x] = 1;
    }
  }
  int MAX = 0;
  int ans = 0;
  for (map<string, map<int, int> >::iterator it1 = dict.begin();
       it1 != dict.end(); ++it1) {
    if (is_reverse(it1->first)) {
      int cur = 0;
      for (map<int, int>::reverse_iterator it = (it1->second).rbegin();
           it != (it1->second).rend(); ++it) {
        int x = it->first, num = it->second;
        if (cur != 0) {
          if (cur + x <= 0) break;
          if (x < 0) MAX = max(MAX, -x);
          ans += cur + x;
          --num;
          cur = 0;
        }
        if (x <= 0) break;
        ans += num / 2 * x * 2;
        cur = x * (num & 1);
      }
      MAX = max(MAX, cur);
    } else {
      string tmp = rev(it1->first);
      if (it1->first < tmp && dict.count(tmp)) {
        map<int, int>::reverse_iterator st = dict[tmp].rbegin(),
                                        ed = dict[tmp].rend();
        for (map<int, int>::reverse_iterator it = it1->second.rbegin(),
                                             it2 = st;
             it != it1->second.rend() && it2 != ed;) {
          int x1 = it->first, x2 = it2->first;
          int num1 = it->second, num2 = it2->second;
          if (x1 + x2 <= 0) break;
          int num = min(num1, num2);
          ans += (x1 + x2) * num;
          it->second -= num;
          if (it->second == 0) ++it;
          it2->second -= num;
          if (it2->second == 0) ++it2;
        }
      }
    }
  }
  printf("%d\n", ans + MAX);
}
