#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long maxn = 3e6;
const long long mod = 1e9 + 7;
const long double PI = 4 * atan((long double)1);
long long pw(long long a, long long b, long long md = mod) {
  long long res = 1;
  while (b) {
    if (b & 1) {
      res = (a * res) % mod;
    }
    a = (a * a) % mod;
    b >>= 1;
  }
  return (res);
}
int k, n, a[maxn];
map<string, vector<int> > mp;
string s[maxn];
vector<string> all;
bool mark[maxn];
map<string, int> odd, even;
bool cmp(int i, int j) { return (a[i] > a[j]); }
int ans = 0;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> s[i] >> a[i];
    mp[s[i]].push_back(i);
    ;
    all.push_back(s[i]);
    ;
  }
  sort(all.begin(), all.end());
  all.resize(unique(all.begin(), all.end()) - all.begin());
  int maxx = 0;
  for (auto i : all) {
    sort(mp[i].begin(), mp[i].end(), cmp);
  }
  for (auto i : all) {
    string j = i;
    reverse(j.begin(), j.end());
    if (i == j) {
      int sum = 0;
      for (int k = 0; k < mp[i].size(); k++) {
        sum += a[mp[i][k]];
        if (k % 2 == 0) {
          odd[i] = max(odd[i], sum);
        } else {
          even[i] = max(even[i], sum);
        }
      }
      if (odd[i] > even[i]) {
        maxx = max(maxx, odd[i] - even[i]);
      }
      continue;
    }
    int l = 0, r = 0;
    while (l < mp[i].size() and r < mp[j].size()) {
      if (a[mp[i][l]] + a[mp[j][r]] > 0 and !mark[mp[i][l]] &&
          !mark[mp[j][r]]) {
        ans += a[mp[i][l]] + a[mp[j][r]];
        mark[mp[i][l]] = mark[mp[j][r]] = 1;
      }
      l++, r++;
    }
  }
  bool f = 0;
  for (auto i : all) {
    string j = i;
    reverse(j.begin(), j.end());
    if (i == j) {
      if (odd[i] > even[i]) {
        if (!f and odd[i] - even[i] == maxx) {
          f = 1;
          ans += odd[i];
        } else {
          ans += even[i];
        }
      } else {
        ans += even[i];
      }
    }
  }
  cout << ans;
  return (0);
}
