#include <bits/stdc++.h>
using namespace std;
const int maxn = 300000;
map<string, int> mapper;
int idx = 0;
int revID[maxn];
vector<string> rev;
vector<int> values[maxn];
int getID(string &s) {
  if (mapper.find(s) == mapper.end()) {
    mapper[s] = idx++;
    rev.push_back(s);
  }
  return mapper[s];
}
char temp[maxn];
int main() {
  int n, k;
  scanf("%d%d", &n, &k);
  while (n--) {
    scanf("%s", temp);
    int v;
    scanf("%d", &v);
    string tmp(temp);
    int id = getID(tmp);
    reverse(tmp.begin(), tmp.end());
    revID[id] = getID(tmp);
    values[id].push_back(v);
  }
  int ans = 0, extra = 0, rem = 0;
  for (int i = 0; i < maxn; i++) sort(values[i].begin(), values[i].end());
  for (int i = 0; i < maxn; i++) {
    if (revID[i] == i) {
      int sz = values[i].size();
      while (sz > 1) {
        int v1 = values[i][sz - 1];
        int v2 = values[i][sz - 2];
        if ((v1 + v2) > 0) {
          rem = min(rem, v2);
          ans += v1 + v2;
          values[i].pop_back();
          values[i].pop_back();
          sz -= 2;
        } else
          break;
      }
      if (sz) extra = max(extra, values[i][sz - 1]);
    } else {
      int u = i, v = revID[i];
      int sz1 = values[u].size();
      int sz2 = values[v].size();
      while (sz1 && sz2) {
        int v1 = values[u][sz1 - 1];
        int v2 = values[v][sz2 - 1];
        if ((v1 + v2) > 0) {
          ans += (v1 + v2);
          sz1--;
          sz2--;
          values[u].pop_back();
          values[v].pop_back();
        } else
          break;
      }
    }
  }
  ans = max(ans - rem, ans + extra);
  printf("%d\n", ans);
  return 0;
}
