有道难题--1000分题

Problem Statement
A permutation A[0], A[1], ..., A[N-1] is a sequence containing each integer between 0 and N-1, inclusive, exactly once. Each permutation A of length N has a corresponding child array B of the same length, where B is defined as follows:
B[0] = 0
B[i] = A[B[i-1]], for every i between 1 and N-1, inclusive.
A permutation is considered perfect if its child array is also a permutation. Below are given all permutations for N=3 with their child arrays. Note that for two of these permutations ({1, 2, 0} and {2, 0, 1}) the child array is also a permutation, so these two permutations are perfect.
Permutation Child array
{0, 1, 2} {0, 0, 0}
{0, 2, 1} {0, 0, 0}
{1, 0, 2} {0, 1, 0}
{1, 2, 0} {0, 1, 2}
{2, 0, 1} {0, 2, 1}
{2, 1, 0} {0, 2, 0}
You are given a int[] P containing a permutation of length N. Find a perfect permutation Q of the same length such that the difference between P and Q is as small as possible. The difference between P and Q is the number of indices i for which P[i] and Q[i] are different. If there are several such permutations Q, return the one among them that has the lexicographically smallest child array.
Definition
????
Class:
PerfectPermutationHard
Method:
reorder
Parameters:
int[]
Returns:
int[]
Method signature:
int[] reorder(int[] P)
(be sure your method is public)

Notes
-
int[] A comes before int[] B (with the same length) lexicographically if A has a smaller integer at the first position where the arrays differ.
Constraints
-
P will contain between 1 and 50 elements, inclusive.
-
P will contain each integer between 0 and N-1, inclusive, exactly once, where N is the number of elements in P.
Examples
0)


{2, 0, 1}
Returns: {2, 0, 1 }
This permutation is already perfect.
1)

{4, 0, 5, 2, 1, 3}
Returns: {2, 0, 5, 4, 1, 3 }
Here the smallest possible difference between P and Q is 2. There are 9 possible choices for Q: {2,0,5,4,1,3}, {3,0,5,2,1,4}, {4,0,1,2,5,3}, {4,0,5,1,2,3}, {4,0,5,2,3,1}, {4,2,5,0,1,3}, {4,3,5,2,1,0}, {4,5,0,2,1,3} and {5,0,4,2,1,3}. Among them, {2,0,5,4,1,3} has the lexicographically smallest child array (this array is {0,2,5,3,4,1}).
2)


{2, 7, 3, 0, 6, 4, 5, 1}
Returns: {1, 7, 3, 0, 6, 2, 5, 4 }

3)


{11, 8, 10, 1, 5, 4, 0, 7, 3, 9, 12, 6, 2}
Returns: {1, 8, 10, 2, 5, 7, 0, 9, 3, 11, 12, 6, 4 }

4)


{0, 1, 4, 2, 3, 5}
Returns: {1, 2, 4, 5, 3, 0 }

5)

{0, 2, 6, 5, 7, 3, 1, 4}
Returns: {1, 2, 6, 5, 7, 4, 3, 0 }

英语太菜了,看不懂!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值