#include <bits/stdc++.h>
using namespace std;
int main() {
  int k, n;
  cin >> k >> n;
  map<string, vector<int> > store;
  map<string, vector<int> >::iterator it;
  string s;
  int value;
  int ans = 0;
  int mid = 0;
  for (int i = 0; i < k; i++) {
    cin >> s >> value;
    store[s].push_back(value);
  }
  for (it = store.begin(); it != store.end(); ++it) {
    sort(it->second.begin(), it->second.end());
  }
  for (it = store.begin(); it != store.end(); it++) {
    string current = it->first;
    string rev = current;
    reverse(rev.begin(), rev.end());
    if (rev == current) {
      for (int val, first, second; store[current].size() > 1;
           ans += max(val, 0)) {
        first = store[current].back();
        store[current].pop_back();
        second = store[current].back();
        store[current].pop_back();
        val = first + second;
        if (first > 0 && second < 0) {
          mid = max(mid, first - max(val, 0));
        }
      }
      if (store[current].size()) {
        mid = max(mid, store[current].back());
        store[current].pop_back();
      }
    } else {
      for (; !store[current].empty() && !store[rev].empty();
           store[current].pop_back(), store[rev].pop_back()) {
        ans = ans + max(store[current].back() + store[rev].back(), 0);
      }
    }
  }
  ans = mid + ans;
  cout << ans;
  return 0;
}
