#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; 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) { int i = 0; while(i < stands[start].size()) { if(samples[stands[start][i]] == 1) break; result--; samples[stands[start][i]]--; i++; } if(i == stands[start].size()) { moved_start = true; start = (start + 1) % n; best_result = min(result, best_result); continue; } i--; //Revert move of start while(i != -1) { result++; samples[stands[start][i]]++; i--; } 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; }