BFFs (Large)

Each kid points to one BFF; find the largest circular seating where everyone sits next to their BFF.

Medium7GraphDFSDynamic programmingImplementationNo attempts yetTime limit5sMemory limit512 MB

Problem

You are a teacher at the brand new Little Coders kindergarten. You have NN kids in your class, and each one has a different student ID number from 1 through NN. Every kid in your class has a single best friend forever (BFF), and you know who that BFF is for each kid. BFFs are not necessarily reciprocal: B being A's BFF does not imply that A is B's BFF.

Your lesson plan for tomorrow includes an activity in which the participants must sit in a circle. You want to make the activity as successful as possible by building the largest possible circle of kids such that each kid in the circle is sitting directly next to their BFF, either to the left or to the right. Any kids not in the circle watch the activity without participating.

What is the greatest number of kids that can be in the circle?

Input

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case consists of two lines. The first line of a test case contains a single integer NN, the total number of kids in the class. The second line of a test case contains NN integers F1,F2,,FNF_1, F_2, \ldots, F_N, where FiF_i is the student ID number of the BFF of the kid with student ID ii.

Limits

  • 1T1001 \le T \le 100
  • 1FiN1 \le F_i \le N for all ii
  • FiiF_i \ne i for all ii (no kid is their own BFF)
  • 3N10003 \le N \le 1000

Output

For each test case, output one line containing "Case #x: y", where xx is the test case number (starting from 1) and yy is the maximum number of kids that can be arranged in a circle such that each kid in the circle is sitting next to their BFF.

Hint

In sample case #4, the largest possible circle seats the following kids in this order: 7 9 3 10 4 1. (Any reflection or rotation of this circle also works.) The kid with student ID 1 is next to the kid with student ID 7, as required, because the list represents a circle.