Under construction

Still being built. Things may change

Mod-3 Permutation

Interview

Time limit1sMemory limit128 MB

Summary
Count entries by index and value residues mod 3, fix directly swappable pairs first, then resolve each leftover triple with two swaps.
Level

Medium5 of 10

Topics
Greedy, Math, Array
Solved
No attempts yet

Problem

A permutation p0,p1,…,pn−1p_0, p_1, \dots, p_{n-1} of the integers 0,1,…,n−10, 1, \dots, n-1 is called mod-3 when pi mod 3=i mod 3p_i \bmod 3 = i \bmod 3 holds for every index ii. For example, 3, 1, 5, 0, 4, 2 is a mod-3 permutation, while 1, 2, 0, 4, 5, 3 is not.

You are given one permutation. In a single step you can pick two different indices and swap the values at those two positions. Find the minimum number of steps that turns the given permutation into a mod-3 permutation.

Input

The first line contains the number of test cases TT, where 1≤T≤1000001 \le T \le 100000.

Each test case takes two lines. The first line contains an integer nn, and the second line contains nn integers separated by single spaces. Those nn integers are a permutation of 0,1,…,n−10, 1, \dots, n-1. nn satisfies 3≤n≤5013 \le n \le 501 and is always a multiple of 3.

Output

For each test case, print one line in the form Case #x: M, where x is the test case number starting from 1 and M is the minimum number of swaps that turns the given permutation into a mod-3 permutation.

Examples1

  1. Example 1

    Input
    10
    3
    2 0 1
    6
    1 0 3 2 5 4
    6
    4 0 3 5 2 4
    6
    5 3 4 2 0 1
    3
    0 2 1
    9
    5 3 8 6 7 0 1 2 4
    9
    2 1 7 3 5 4 8 6 0
    9
    3 5 2 0 6 4 7 1 8
    9
    5 7 1 8 2 6 0 4 3
    9
    8 3 5 0 6 7 4 2 1
    
    Expected output
    Case #1: 2
    Case #2: 3
    Case #3: 3
    Case #4: 4
    Case #5: 1
    Case #6: 3
    Case #7: 4
    Case #8: 2
    Case #9: 3
    Case #10: 4