#include <bits/stdc++.h>
using namespace std;
const int LIM = 1e5 + 5, MOD = 998244353;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long fastpowMOD(long long a, long long p, long long MOD) {
  if (p == 0) return 1;
  long long z = fastpowMOD(a, p / 2, MOD);
  z = (z * z) % MOD;
  if (p % 2) z = (z * a) % MOD;
  return z;
}
bool seive[13000];
void SieveOfEratosthenes(long long n) {
  memset(seive, true, sizeof(seive));
  for (long long p = 2; p * p <= n; p++)
    if (seive[p] == true)
      for (long long i = p * p; i <= n; i += p) seive[i] = false;
}
long long fastpow(long long a, long long p) {
  if (p == 0) return 1;
  long long z = fastpow(a, p / 2);
  z = (z * z);
  if (p % 2) z = (z * a);
  return z;
}
long long n, k;
long long ch(string s) {
  long long i = 0;
  long long j = s.size() - 1;
  while (i < j) {
    if (s[i] == s[j]) {
      i++;
      j--;
    } else {
      return 0;
    }
  }
  return 1;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> k;
  long long i;
  map<string, long long> my;
  map<string, long long> my1;
  string s;
  long long k = 1;
  vector<long long> v[n + 5];
  vector<long long> ans;
  vector<long long> pal;
  for (i = 0; i < n; i++) {
    string s;
    long long val;
    cin >> s >> val;
    if (my[s] == 0) {
      my[s] = k;
      v[k].push_back(val);
      k++;
    } else {
      long long pre = my[s];
      v[pre].push_back(val);
    }
    if (ch(s)) {
      my1[s] = my[s];
    }
  }
  for (i = 1; i <= k; i++) {
    sort(v[i].begin(), v[i].end());
    reverse(v[i].begin(), v[i].end());
  }
  for (auto it : my) {
    if (my1[it.first] > 0) continue;
    if (it.second > 0) {
      string s = it.first;
      reverse(s.begin(), s.end());
      if (my[s]) {
        long long k1 = it.second;
        long long k2 = my[s];
        for (i = 0; i < v[k1].size() and i < v[k2].size(); i++) {
          ans.push_back(v[k1][i] + v[k2][i]);
        }
        my[s] = 0;
        it.second = 0;
      }
      my[s] = 0;
      it.second = 0;
    }
  }
  sort(ans.begin(), ans.end());
  reverse(ans.begin(), ans.end());
  long long ans1 = 0;
  for (auto it : ans) {
    if (it <= 0) break;
    ans1 += it;
  }
  long long max1 = 0;
  for (auto it : my1) {
    if (it.second == 0) continue;
    long long p1 = it.second;
    long long sz = v[p1].size();
    for (i = 0; i < sz; i += 2) {
      if (i + 1 == sz) {
        max1 = max(max1, v[p1][i]);
        break;
      }
      long long answ = v[p1][i] + v[p1][i + 1];
      if (answ < 0) {
        max1 = max(max1, v[p1][i]);
        break;
      } else {
        ans1 += answ;
        max1 = max(max1, -v[p1][i + 1]);
      }
    }
  }
  cout << ans1 + max1;
}
