#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  int n, k;
  cin >> n >> k;
  map<string, vector<int> > data;
  for (int i = 0; i < n; i++) {
    string str;
    int val;
    cin >> str >> val;
    data[str].push_back(val);
  }
  map<string, vector<int> >::iterator it;
  for (it = data.begin(); it != data.end(); it++) {
    sort(it->second.begin(), it->second.end());
  }
  long long ans = 0;
  long long tempMax = 0;
  for (it = data.begin(); it != data.end(); it++) {
    string key1 = it->first;
    string key2(key1);
    reverse(key2.begin(), key2.end());
    while (1) {
      if (key1.compare(key2) == 0) {
        if (data[key1].empty()) break;
        int a, b = 0;
        a = data[key1][data[key1].size() - 1];
        if (data[key1].size() >= 2) {
          b = data[key1][data[key1].size() - 2];
          long long temp = a + b;
          if (temp > 0) {
            ans += temp;
            b *= -1;
            tempMax = tempMax > b ? tempMax : b;
          } else {
            tempMax = tempMax > a ? tempMax : a;
          }
        } else {
          tempMax = tempMax > a ? tempMax : a;
        }
      } else {
        if (data[key1].empty() || data[key2].empty()) break;
        long long temp = data[key1][data[key1].size() - 1] +
                         data[key2][data[key2].size() - 1];
        if (temp > 0) ans += temp;
      }
      if (!data[key1].empty()) data[key1].pop_back();
      if (!data[key2].empty()) data[key2].pop_back();
    }
  }
  cout << ans + tempMax << endl;
}
