#include <bits/stdc++.h>
using namespace std;
long long ans, C;
struct Node {
  vector<int> val;
  int next[26];
  Node() { memset(next, -1, sizeof next); }
};
Node B[100100];
int sz(1);
void insert(const string &s, int val) {
  int v(0);
  char c;
  for (int i(0); i < s.size(); ++i) {
    c = s[i] - 'a';
    if (B[v].next[c] == -1) B[v].next[c] = sz++;
    v = B[v].next[c];
  }
  B[v].val.push_back(val);
}
bool is_pal(const string &s) {
  for (int i(0), j(s.size() - 1); i < j; ++i, --j)
    if (s[i] != s[j]) return false;
  return true;
}
string rev(const string &s) {
  string res(s);
  reverse(res.begin(), res.end());
  return res;
}
int find_s(const string &s) {
  int v(0);
  char c;
  for (int i(0); i < s.size(); ++i) {
    c = s[i] - 'a';
    if (B[v].next[c] == -1) return -1;
    v = B[v].next[c];
  }
  return v;
}
bool was[100100];
void calc_pal(vector<int> &v) {
  sort(v.begin(), v.end());
  int p(v.size() - 1);
  while (p > 0 && v[p] > 0) {
    if (v[p] + v[p - 1] > 0) {
      ans += v[p] + v[p - 1];
      if (v[p - 1] < 0) C = max(C, (long long)-v[p - 1]);
    } else
      C = max(C, (long long)v[p]);
    -- --p;
  }
  if (p == 0) C = max(C, (long long)v[p]);
}
void calc_usual(vector<int> &v1, vector<int> &v2) {
  sort(v1.begin(), v1.end());
  sort(v2.begin(), v2.end());
  int p(v1.size() - 1), q(v2.size() - 1);
  while (p >= 0 && q >= 0 && v1[p] + v2[q] > 0) {
    ans += v1[p] + v2[q];
    --p, --q;
  }
}
void dfs(int v, string &cur) {
  if (B[v].val.size() && !was[v]) {
    was[v] = true;
    if (is_pal(cur))
      calc_pal(B[v].val);
    else {
      int u(find_s(rev(cur)));
      if (u != -1) {
        was[u] = true;
        calc_usual(B[v].val, B[u].val);
      }
    }
  }
  for (int i(0); i < 26; ++i)
    if (B[v].next[i] != -1) {
      cur += char(i + 'a');
      dfs(B[v].next[i], cur);
      cur = cur.substr(0, cur.size() - 1);
    }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, k;
  cin >> n >> k;
  string s;
  int val;
  while (n--) {
    cin >> s >> val;
    insert(s, val);
  }
  string meow;
  dfs(0, meow);
  cout << ans + C;
}
