//#define _GLIBCXX_DEBUG #include using namespace std; #define endl '\n' #define lfs cout<= (ll)(n); i--) using ll = long long; using ld = long double; const ll MOD1 = 1e9+7; const ll MOD9 = 998244353; const ll INF = 1e18; using P = pair; template bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;} template bool chmax(T1 &a,T2 b){if(a void ans(bool x,T1 y,T2 z){if(x)cout< void debug(vector>&v,ll h,ll w){for(ll i=0;i&v,ll h,ll w){for(ll i=0;i void debug(vector&v,ll n){if(n!=0)cout< vector>vec(ll x, ll y, T w){ vector>v(x,vector(y,w));return v;} ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;} vectordx={1,0,-1,0,1,1,-1,-1}; vectordy={0,1,0,-1,1,-1,1,-1}; template vector make_v(size_t a,T b){return vector(a,b);} template auto make_v(size_t a,Ts... ts){ return vector(a,make_v(ts...)); } template ostream &operator<<(ostream &os, const pair&p){ return os << p.first << " " << p.second; } int main(){ cin.tie(nullptr); ios_base::sync_with_stdio(false); ll res=0,buf=0; bool judge = true; ll n,k;cin>>n>>k; vectors(n); vectorc(n); rep(i,0,n)cin>>s[i]>>c[i]; auto cnt=vec(n,3,0LL); rep(i,0,n)rep(j,0,s[i].size()){ if(s[i][j]=='J')cnt[i][0]++; if(s[i][j]=='O')cnt[i][1]++; if(s[i][j]=='I')cnt[i][2]++; } vectordp(3*k+1,INF); dp[0]=0; string joi="JOI"; rep(i,0,3*k){ ll p=i/k; rep(j,0,n){ if(p==min(2LL,(i+cnt[j][p])/k)){ chmin(dp[min(3*k,i+cnt[j][p])],dp[i]+c[j]); } else{ ll now=i; for(auto c:s[j]){ if(now!=3*k&&c==joi[now/k])now++; } chmin(dp[now],dp[i]+c[j]); } } } ans(dp[3*k]==INF,-1,dp[3*k]); return 0; }