#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;
map<string, priority_queue<int> > q;
string a[maxn], temp;
int main() {
  int n, k, val, now, x = 0;
  scanf("%d%d", &n, &k);
  for (int i = 1; i <= n; i++) {
    cin >> a[i] >> val;
    q[a[i]].push(val);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    temp = a[i];
    reverse(temp.begin(), temp.end());
    if (temp != a[i]) {
      while (q[temp].empty() == 0 && q[a[i]].empty() == 0 &&
             q[temp].top() + q[a[i]].top() > 0) {
        ans += q[temp].top() + q[a[i]].top();
        q[temp].pop();
        q[a[i]].pop();
      }
    } else {
      while (q[temp].size() > 1) {
        now = q[temp].top();
        q[temp].pop();
        if (q[temp].top() + now > 0) {
          ans += now + q[temp].top();
          x = min(x, q[temp].top());
          q[temp].pop();
        } else {
          q[temp].push(now);
          break;
        }
      }
    }
  }
  x = -x;
  for (int i = 1; i <= n; i++) {
    temp = a[i];
    reverse(temp.begin(), temp.end());
    if (temp == a[i] && q[temp].empty() == 0) x = max(x, q[temp].top());
  }
  cout << ans + x << endl;
  return 0;
}
