#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
bool check_pal(string s) {
  long long n = s.length();
  for (long long i = 0; i < n; i++) {
    if (s[i] != s[n - 1 - i]) {
      return false;
    }
  }
  return true;
}
string rev(string s) {
  string tmp;
  for (long long i = s.length() - 1; i >= 0; i--) {
    tmp += s[i];
  }
  return tmp;
}
vector<pair<string, vector<long long>>> v;
long long ans = 0;
long long dp[100005][2];
long long rec(long long ind, long long flag) {
  if (ind == v.size()) {
    return 0;
  }
  long long &anss = dp[ind][flag];
  if (anss >= 0) {
    return anss;
  }
  anss = 0;
  if (flag) {
    anss = max(anss, rec(ind + 1, flag));
    if (v[ind].second.size() >= 2) {
      anss = max(anss, v[ind].second[v[ind].second.size() - 1] +
                           v[ind].second[v[ind].second.size() - 2] +
                           rec(ind + 1, flag));
    }
  } else {
    anss = max(anss, v[ind].second.back() + rec(ind + 1, 1));
    anss = max(anss, rec(ind + 1, flag));
    if (v[ind].second.size() >= 2) {
      anss = max(anss, v[ind].second[v[ind].second.size() - 1] +
                           v[ind].second[v[ind].second.size() - 2] +
                           rec(ind + 1, flag));
    }
  }
  return anss;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long k, n;
  cin >> k >> n;
  memset(dp, -1, sizeof(dp));
  map<string, vector<long long>> mp;
  for (long long i = 0; i < k; i++) {
    string s;
    long long b;
    cin >> s >> b;
    mp[s].push_back(b);
  }
  for (auto &x : mp) {
    sort(x.second.begin(), x.second.end());
  }
  for (auto &x : mp) {
    string tmp = rev(x.first);
    long long flag = check_pal(x.first);
    while (true) {
      if (flag) {
        if (x.second.size() >= 2) {
          if (x.second[x.second.size() - 1] > 0 &&
              x.second[x.second.size() - 2] > 0) {
            ans +=
                x.second[x.second.size() - 1] + x.second[x.second.size() - 2];
            x.second.pop_back();
            x.second.pop_back();
          } else {
            break;
          }
        } else {
          break;
        }
      } else {
        if (x.second.empty()) {
          break;
        }
        long long a = x.second.back();
        x.second.pop_back();
        if (mp[tmp].empty()) {
          break;
        }
        long long b = mp[tmp].back();
        mp[tmp].pop_back();
        if (a + b > 0) {
          ans += (a + b);
        } else {
          break;
        }
      }
    }
  }
  for (auto &x : mp) {
    if (check_pal(x.first) && x.second.size()) {
      v.push_back({x.first, x.second});
    }
  }
  ans += rec(0, 0);
  cout << ans << "\n";
}
