#include <bits/stdc++.h>
using namespace std;
struct Node {
  vector<int> btfl;
  int next[26];
  Node();
};
Node::Node() { memset(next, -1, sizeof next); }
struct Bohr {
  vector<Node> B;
  Bohr();
  void insert(string &s, int beauty);
  int find_s(string &s);
  void dfs(int v, string &cur);
};
Bohr b;
long long ans, mid;
bool was[100001];
void count_pal(vector<int> &v);
void count_us(vector<int> &one, vector<int> &two);
bool is_pal(string &s);
string rev(string s);
Bohr::Bohr() { B.resize(1, Node()); }
void Bohr::insert(string &s, int beauty) {
  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] = B.size();
      B.push_back(Node());
    }
    v = B[v].next[c];
  }
  B[v].btfl.push_back(beauty);
}
int Bohr::find_s(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;
}
void Bohr::dfs(int v, string &cur) {
  int u;
  string new_s;
  if (B[v].btfl.size() && !was[v]) {
    was[v] = true;
    if (is_pal(cur)) {
      count_pal(B[v].btfl);
    } else {
      new_s = rev(cur);
      u = find_s(new_s);
      if (u != -1) {
        was[u] = true;
        count_us(B[v].btfl, B[u].btfl);
      }
    }
  }
  for (int i(0); i < 26; ++i) {
    if (B[v].next[i] == -1) continue;
    cur += char(i + 'a');
    dfs(B[v].next[i], cur);
    cur = cur.substr(0, cur.size() - 1);
  }
}
void count_pal(vector<int> &v) {
  sort(v.begin(), v.end());
  int i(v.size() - 1);
  while (i > 0 && v[i] > 0) {
    if (v[i] + v[i - 1] > 0) {
      if (v[i - 1] < 0) mid = max(mid, (long long)v[i - 1] * -1);
      ans += (long long)v[i] + v[i - 1];
    } else
      mid = max(mid, (long long)v[i]);
    i -= 2;
  }
  if (i == 0) mid = max(mid, (long long)v[i]);
}
void count_us(vector<int> &one, vector<int> &two) {
  sort(one.begin(), one.end());
  sort(two.begin(), two.end());
  int i(one.size() - 1), j(two.size() - 1);
  while (one[i] + two[j] > 0 && i >= 0 && j >= 0) {
    ans += (long long)one[i] + two[j];
    i--, j--;
  }
}
bool is_pal(string &s) {
  if (s == rev(s)) return true;
  return false;
}
string rev(string s) {
  reverse(s.begin(), s.end());
  return s;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, k, a;
  cin >> k >> n;
  string s;
  Bohr();
  while (k--) {
    cin >> s >> a;
    b.insert(s, a);
  }
  string meow;
  b.dfs(0, meow);
  cout << (long long)ans + mid;
  return 0;
}
