#include <bits/stdc++.h>
using namespace std;
int k, n, a;
string s;
long long ans, ans2, lastop1, lastop2;
map<string, vector<int> > mop;
map<string, int> vis;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> k >> n;
  for (int i = 0; i < k; i++) {
    cin >> s >> a;
    mop[s].push_back(a);
  }
  for (auto i : mop) sort(mop[i.first].rbegin(), mop[i.first].rend());
  for (auto i : mop) {
    string s1 = i.first;
    if (vis[s1]) continue;
    string s2 = s1;
    reverse(s2.begin(), s2.end());
    vis[s1] = vis[s2] = 1;
    if (s1 == s2) {
      long long op1 = 0, op2 = 0;
      for (int j = 1; j < mop[s1].size() && mop[s1][j] + mop[s1][j - 1] > 0;
           j += 2)
        op1 += mop[s1][j] + mop[s1][j - 1];
      while (!mop[s1].empty() && mop[s1].back() < 0) mop[s1].pop_back();
      if ((int)mop[s1].size() % 2) op2 = mop[s1].back();
      for (int j = 1; j < mop[s1].size(); j += 2)
        op2 += mop[s1][j] + mop[s1][j - 1];
      if (-lastop2 + lastop1 + op2 >= op1) {
        ans = ans - lastop2 + lastop1 + op2;
        lastop1 = op1, lastop2 = op2;
      } else
        ans += op1;
      continue;
    }
    int lst = min((int)mop[s1].size(), (int)mop[s2].size());
    for (int j = 0; j < lst && mop[s1][j] + mop[s2][j] >= 0; j++)
      ans += mop[s1][j] + mop[s2][j];
  }
  cout << ans + ans2;
}
