#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stack>
#include<cstring>
#include<set>
#include<iterator>
#include<list>
#include<deque>
#include<queue>
#include<map>
#include<cmath>
#include<sstream>
#include<cstdio>
#include<ctime>
#include<iomanip>
//#include<unordered_set>
using namespace std;
#define lowbit(x) x&(-x)
typedef long long ll;
typedef pair<int, int> P;
const int N = 2e2 + 10;
const int M = 1e4 + 10;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
vector<int> g[N];
map<string, int> ma;
int price[N];
int num[N];
int dp[N][N];
int fa[N];
int n, m;
void dfs(int x)
{
num[x] = 1;
for (int i = 0; i < g[x].size(); i++)
{
int y = g[x][i];
//cout << x << " " << y << endl;
dfs(y);
num[x] += num[y];
}
dp[x][0] = 0;
for (int i = 1; i <= n; i++)
{
dp[x][i] = inf;
}
dp[x][num[x]] = price[x];
for (int i = 0; i < g[x].size(); i++)
{
int y = g[x][i];
for (int j = num[x]; j >= 0; j--)
{
for (int k = 0; k <= j && k <= num[y]; k++)
{
dp[x][j] = min(dp[x][j], dp[x][j - k] + dp[y][k]);
//printf("dp[%d][%d] == %d\n",x,j, dp[x][j]);
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
string s;
while (getline(cin,s))
{
memset(fa, 0, sizeof(fa));
if (s == "#")
break;
stringstream temps(s);
temps >> n >> m;
for (int i = 0; i <= n; i++)
g[i].clear();
ma.clear();
int cnt = 0;
for (int i = 1; i <= n; i++)
{
string name;
int x;
getline(cin,s);
stringstream ss(s);
ss >> name >> x;
if (!ma[name])
{
ma[name] = ++cnt;
}
int u = ma[name];
price[u] = x;
while (ss)
{
string temp;
ss >> temp;
if (temp == "")
continue;
if (!ma[temp])
{
ma[temp] = ++cnt;
}
int v = ma[temp];
g[u].push_back(v);
fa[v] = 1;
}
}
price[0] = inf;
for (int i = 1; i <= n; i++)
{
if (!fa[i])
{
g[0].push_back(i);
}
}
dfs(0);
int ans = inf;
for (int i = m; i <= n; i++)
{
ans = min(ans, dp[0][i]);
//printf("dp[0][%d] == %d\n", i, dp[0][i]);
}
printf("%d\n", ans);
}
return 0;
}