#include #include #define MAX 1000005 #define INF 50000000000 #define LL long long using namespace std; vector sizes(MAX); vector> stands; vector occur; LL best_size = INF; LL current_size = 0; LL have = 0; LL included = 0; void add(LL t) { ++included; current_size += sizes[t]; for (auto x : stands[t]) { ++occur[x]; if (occur[x] == 1) { ++have; } } } void remove(LL t) { --included; current_size -= sizes[t]; for (auto x : stands[t]) { --occur[x]; if (occur[x] == 0) { --have; } } } int main() { std::iostream::sync_with_stdio(false); LL N, K; while (cin >> N >> K) { stands.assign(N, vector()); occur.assign(K, -1); for (int i = 0; i < N; ++i) { LL M; cin >> M; sizes[i] = M; for (int j = 0; j < M; ++j) { LL akt; cin >> akt; akt--; if (occur[akt] != i) { stands[i].push_back(akt); occur[akt] = i; } } } occur.assign(K, 0); // half-open interval LL tail = 0; LL head = 1 % N; included = 0; have = 0; best_size = INF; current_size = 0; add(0); for (tail = 0; tail < N; ++tail) { while (have != K && included != N) { add(head); head = (head + 1) % N; } if (have == K) { best_size = min(best_size, current_size); } remove(tail); } if (best_size == INF) { cout << "-1" << endl; } else { cout << best_size << endl; } } return 0; }