#include <bits/stdc++.h>
using namespace std;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  map<string, vector<int> > mda;
  int n, k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    int cost;
    cin >> cost;
    mda[s].push_back(cost);
  }
  for (auto &c : mda) {
    sort(c.second.rbegin(), c.second.rend());
  }
  long long ans = 0;
  long long odd = 0;
  for (auto &c : mda) {
    string t = c.first;
    reverse(t.begin(), t.end());
    if (t < c.first) {
      long long best = 0;
      long long s = 0;
      for (int i = 0; i < (int)c.second.size() && i < mda[t].size(); i++) {
        s += c.second[i];
        s += mda[t][i];
        best = max(best, s);
      }
      ans += best;
    } else if (t == c.first) {
      long long s = 0;
      int mda = 0;
      long long last = 0;
      long long fir = -1e18;
      for (int i = 0; i < (int)c.second.size(); i++) {
        if (c.second[i] > 0) {
          last = c.second[i];
          s += c.second[i];
          mda++;
        } else {
          fir = c.second[i];
          break;
        }
      }
      if (mda % 2 == 0) {
        ans += s;
      } else {
        long long me = max(s - last, s + fir);
        long long delta_odd = s - me;
        ans += me;
        odd = max(odd, delta_odd);
      }
    }
  }
  cout << ans + odd << endl;
}
