#include <bits/stdc++.h>
using namespace std;
int n, k, x, y, sum, cnt, ans, maxx;
char s[100005];
vector<int> v[100005];
map<string, int> m;
map<int, string> go;
bool used[100005];
int main() {
  scanf("%d %d", &k, &n);
  for (int i = 0; i < k; i++) {
    scanf("%s %d", s, &y);
    string t = s;
    if (m.find(t) == m.end()) {
      m[t] = x++;
      go[m[t]] = t;
      v[m[t]].push_back(y);
    } else {
      v[m[t]].push_back(y);
    }
  }
  for (int i = 0; i < x; i++)
    sort(v[i].begin(), v[i].end()), reverse(v[i].begin(), v[i].end());
  for (int i = 0; i < x; i++) {
    if (used[i]) continue;
    string t = go[i];
    reverse(t.begin(), t.end());
    if (m.find(t) != m.end()) {
      int j = m[t];
      used[j] = true;
      if (i == j) {
        for (int it = 0; it < v[i].size(); it += 2) {
          if (it + 1 == v[i].size()) {
            maxx = max(maxx, v[i][it]);
            break;
          }
          if (v[i][it] + v[i][it + 1] > 0) {
            ans += v[i][it] + v[i][it + 1];
            maxx = max(maxx, -v[i][it + 1]);
          } else if (v[i][it + 1] < 0)
            maxx = max(maxx, v[i][it]);
        }
        continue;
      }
      for (int it = 0; it < min(v[i].size(), v[j].size()); it++) {
        if (v[i][it] + v[j][it] > 0) {
          ans += v[i][it] + v[j][it];
        } else
          break;
      }
    }
  }
  printf("%d\n", ans + maxx);
  return 0;
}
