Given a circular sequence of sample boxes, find the shortest consecutive run whose multiset union covers all brands 1 to K, and report its total sample count.
Hard8Sliding windowTwo pointersArrayImplementationNo attempts yetTime limit3sMemory limit512 MBA circular path lined with ice cream stands runs through the park, built to keep visitors moving between the attractions. All stands share one discount system. When a customer buys ice cream at a stand, that customer automatically gets a one day discount at the next stand on the path. Anyone who starts at some stand and keeps following the discount to the next stand goes around the whole circle and comes back to the stand where they started.
The stands sell ice cream of many brands. Each stand also sells a sample box holding small samples of popular brands. The number of samples in a box depends on the stand, and different stands may put different brands into their boxes. Every box holds samples of at least one brand. A brand may appear in a box several times, or not at all. A stand sells only one kind of sample box, so the brands inside that stand's box are always the same.
Quido and Hugo are going to use the discount system. They pick a stand to start at, follow the direction of the discounts, and buy one sample box at every stand of a consecutive run. Their goal is to collect at least one sample of every brand from 1 to K. At the same time they respect their stomach capacity, so they want the total number of samples they buy to be as small as possible. The run may pass the end of the circle and continue at the first stand, and it never visits the same stand twice.
The input holds several test cases and continues to the end of the file. Each case starts with a line containing two integers N and K separated by a space (1≤N,K≤106). N is the number of ice cream stands, K is the number of different brands, and the brands are numbered from 1 to K. The next N lines describe the stands in their visiting order, and the stand on the last line is followed by the stand on the first line. Each such line holds the list of brands of all samples in the sample box sold at that stand. The list starts with one positive integer L giving its length, followed by L integers. Each list item is the brand of one sample in the box. Some brand numbers may be missing from every box. In one test case, buying one sample box at every stand collects at most 107 samples.
For each test case, print a single line with one integer, the smallest number of samples Quido and Hugo have to buy to obtain a sample of every brand from 1 to K. If no run of consecutive stands collects all K brands, print -1.