#include <bits/stdc++.h>
using namespace std;
string second[100005], rs[100005];
int a[100005];
vector<int> v[2 * 100005];
bool done[2 * 100005];
map<string, int> mp;
vector<int> extra;
int main() {
  {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
  };
  int n, k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> second[i] >> a[i];
    for (int j = k - 1; j >= 0; j--) rs[i] += second[i][j];
  }
  int cnt = 0;
  for (int i = 0; i < n; i++) {
    if (mp.find(second[i]) == mp.end()) {
      mp[second[i]] = ++cnt;
    }
    if (mp.find(rs[i]) == mp.end()) {
      mp[rs[i]] = ++cnt;
    }
  }
  for (int i = 0; i < n; i++) {
    v[mp[second[i]]].push_back(a[i]);
  }
  for (int i = 1; i <= cnt; i++) sort(v[i].rbegin(), v[i].rend());
  int ans = 0;
  for (int i = 0; i < n; i++) {
    int x = mp[second[i]], y = mp[rs[i]];
    if (done[x]) continue;
    done[x] = 1, done[y] = 1;
    if (x != y) {
      for (int i = 0; i < min(v[x].size(), v[y].size()); i++) {
        if (v[x][i] + v[y][i] < 0) break;
        ans += v[x][i] + v[y][i];
      }
    } else {
      vector<int> pos, neg;
      for (int i = 0; i < v[x].size(); i++) {
        if (v[x][i] >= 0)
          pos.push_back(v[x][i]);
        else
          neg.push_back(v[x][i]);
      }
      if (pos.size() % 2 == 0) {
        for (int j : pos) ans += j;
      } else {
        for (int j : pos) ans += j;
        ans -= pos.back();
        if (neg.empty() || pos.back() + neg[0] < 0) {
          extra.push_back(pos.back());
        } else {
          ans += pos.back() + neg[0];
          extra.push_back(neg[0]);
        }
      }
    }
  }
  int mx = 0;
  for (int i : extra) {
    mx = max(mx, ans + abs(i));
  }
  cout << max(mx, ans) << endl;
}
