TopCoder problem "CardsCheating" used in SRM 415 (Division II Level Three)



Problem Statement

    You are a dealer in some card game for 3 players (numbered 0, 1, 2). The game uses a deck of N cards, numbered 0 to N-1. First you perform a few shuffles of the deck and then give cards to the players. The card at position 0 goes to player 0, the card at position 1 goes to player 1, the card at position 2 goes to player 2, the card at position 3 goes to player 0, and so on. But you want to cheat. You know the initial order of the cards in the deck, and you want each card to go to a specific player. You want to know the minimal number of shuffles required to give the cards to the desired players. You can only perform the shuffle given in the int[] shuffle. After performing one shuffle, the card that was at position i in the deck will be at position shuffle[i]. You want the card that's initially at position i in the deck to go to player cards[i]. Return the minimal number of shuffles needed to achieve the goal or -1 if it is impossible.
 

Definition

    
Class:CardsCheating
Method:numberOfShuffles
Parameters:int[], int[]
Returns:int
Method signature:int numberOfShuffles(int[] cards, int[] shuffle)
(be sure your method is public)
    
 

Constraints

-cards will contain between 3 and 48 elements, inclusive.

-Each element of cards will be 0, 1 or 2.

-The number of elements in cards will be a multiple of 3.

-shuffle and cards will contain the same number of elements.

-All elements in shuffle will be distinct.

-Each element of shuffle will be between 0 and N-1, inclusive, where N is the number of elements in shuffle..

 

Examples

0)
    
{0,1,2,0,1,2}
{1,4,0,3,2,5}
Returns: 0
No shuffles are needed.
1)
    
{2,0,1}
{1,2,0}
Returns: 2
Shuffle the deck two times.
2)
    
{1,1,2,0,2,0,1,0,2,2,1,0}
{5,0,9,7,1,8,3,10,4,11,6,2}
Returns: 59
3)
    
{1,0,2}
{0,2,1}
Returns: -1

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9934

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13506&pm=9934

Writer:

Gluk

Testers:

PabloGilberto , bmerry , Olexiy , ivan_metelsky

Problem categories:

Simulation