#include <bits/stdc++.h>
using namespace std;
long long const N = 1e5 + 15, mod = 1e9 + 7, inf = 1e17, sq = 500, md = 1299817,
                base = 27;
long long a[N], b[N], c[N], dp[N], k;
multiset<long long, greater<long long> > st[N];
pair<long long, string> p[N];
map<string, long long> mp;
long long phash(string s, long long MD) {
  long long pbase = 1, ans = 0;
  for (int i = 0; i < k; i++) {
    ans = (ans + ((s[i] - 'a') * pbase)) % MD;
    pbase = (pbase * base) % MD;
  }
  return ans;
}
bool palindrome(string s) {
  for (int i = 0; i <= k / 2; i++) {
    if (s[i] != s[k - i - 1]) return false;
  }
  return true;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n, hs, hs1, ans = 0;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> p[i].second >> p[i].first;
    mp[p[i].second] = i + 1;
  }
  sort(p, p + n, greater<pair<long long, string> >());
  for (int i = 0; i < n; i++) {
    hs = mp[p[i].second];
    st[hs].insert(p[i].first);
  }
  long long f = 0, mx = 0;
  for (int i = 0; i < n; i++) {
    hs = mp[p[i].second];
    if (palindrome(p[i].second))
      f = 1;
    else
      f = 0;
    if (st[hs].size() && *(st[hs].begin()) == p[i].first)
      st[hs].erase(st[hs].begin());
    else
      continue;
    reverse(p[i].second.begin(), p[i].second.end());
    hs = mp[p[i].second];
    if (hs && st[hs].size() && (p[i].first + *(st[hs].begin())) > 0) {
      if (f) mx = max(mx, -1 * (*(st[hs].begin())));
      ans += p[i].first + *(st[hs].begin());
      st[hs].erase(st[hs].begin());
    } else if (f)
      mx = max(mx, p[i].first);
  }
  cout << ans + mx << endl;
}
