//Let's join Kaede Takagaki Fan Club !! #include #include #include using namespace std; typedef long long ll; typedef pair P; typedef pair P1; typedef pair P2; #define pu push #define pb push_back #define mp make_pair #define eps 1e-7 #define INF 1000000000 #define fi first #define sc second #define rep(i,x) for(int i=0;i void dmp(T a){ rep(i,a.size()) cout << a[i] << " "; cout << endl; } template bool chmax(T&a, T b){ if(a < b){ a = b; return 1; } return 0; } template bool chmin(T&a, T b){ if(a > b){ a = b; return 1; } return 0; } template void g(T &a){ cin >> a; } template void o(const T &a,bool space=false){ cout << a << (space?' ':'\n'); } //ios::sync_with_stdio(false); const int mod = 1000000007; template void add(T&a,T b){ a+=b; if(a >= mod) a-=mod; } int n, kk; string s[105]; int c[105]; ll dp[3][100005]; int main(){ ios::sync_with_stdio(false); cin >> n >> kk; repn(i, n) cin >> s[i] >> c[i]; rep(i, 3) rep(j, 100005) dp[i][j] = 1e18; string sp = "JOI"; rep(x, 3){ dp[x][0] = 0; repn(i, n){ int k = 0; for(auto at:s[i]) k += (at == sp[x]); rep(j, 100005){ if(j+k >= 100005) continue; chmin(dp[x][j+k], dp[x][j] + c[i]); } } } for(int i=100003;i>=0;i--) rep(j, 3) chmin(dp[j][i], dp[j][i+1]); //JO & OI & JOI vectorvec[2]; ll ans = 1e18; repn(i, n){ rep(j, s[i].size()+1){ int a = 0, b = 0; rep(k, j) a += (s[i][k] == 'J'); for(int k=j;k= kk){ chmin(ans, 1LL*c[i] + dp[0][max(0, kk-a)] + dp[2][max(0, kk-d)]); } } } } for(auto at:vec[0]) for(auto at2:vec[1]){ int z1 = max(0, kk - at.sc.fi); int z2 = max(0, kk - at.sc.sc - at2.sc.fi); int z3 = max(0, kk - at2.sc.sc); chmin(ans, 1LL*at.fi + at2.fi + dp[0][z1] + dp[1][z2] + dp[2][z3]); } if(ans > 5e17) ans = -1; o(ans); }