#include #include #include using namespace std; int main() { ios::sync_with_stdio(false); int samples[1000001]; int n, k; while(cin >> n >> k) { for(int i = 0; i <= k; i++) samples[i] = 0; set stuff; vector > stands(n); for(int stand = 0; stand < n; stand++) { int l; cin >> l; stands[stand] = vector(l); for(int i = 0; i < l; i++) { cin >> stands[stand][i]; } } int start = 0; int end = 0; int result = 0; int best_result = 0; stuff.clear(); while(stuff.size() < k && end < n) { for(vector::iterator it = stands[end].begin(); it != stands[end].end(); it++) { samples[*it]++; result++; stuff.insert(*it); } end++; } best_result = result; if(stuff.size() < k) { cout << -1 << endl; continue; } bool moved_start = false; while(!moved_start || start != 0) { vector::iterator it = stands[start].begin(); while(it != stands[start].end()) { if(samples[*it] == 1) break; result--; samples[*it]--; it++; } if(it == stands[start].end()) { moved_start = true; start = (start + 1) % n; best_result = min(result, best_result); continue; } if(it != stands[start].begin()) it--; //Revert move of start while(it != stands[start].begin()) { result++; samples[*it]++; it--; } result++; samples[*it]++; for(vector::iterator it = stands[end].begin(); it != stands[end].end(); it++) { samples[*it]++; result++; } end = (end + 1) % n; } for(int stand = 0; stand < n; stand++) stands[stand].clear(); cout << best_result << endl; } return 0; }