题目简述:
牌面有0,1,2,3,4,5,6,7,8,9;
现在需要洗n张牌,从上到下依次是第1张,第二张,…,第n张。
首先把n张牌平均分两堆,左手上半堆,右手下半堆,若n为奇数,则左手比右手多一张。
奇数次洗牌:先放下右手最后一张牌,再放下左手最后一张牌…
偶数次洗牌:先放下左手最后一张牌,再放下右手最后一张牌…
如:1 2 3 4 5 6
分牌:左手:1,2,3 右手:4,5,6
第1次洗牌变为:1,4,2,5,3,6
第2次洗牌变为:5,1,3,4,6,2
输入描述:
给出牌数n,空格后为洗牌次数k,空格后从上到下给出牌序列
输出描述:
k次洗牌后的牌序列,空格隔开
实例:
input:
7 2 1 2 3 4 5 6 7
output:
1 6 2 4 5 7 3
实例解释:
7张牌为1到7,洗2次。
分牌:左手1234,右手567;
第一次洗牌先放右手7,再放左手4,最后为7463521。
注意:先放的牌在下面,后放的在上面,因此牌序列为1253647
再分牌:左手1253,右手647
第二次洗牌先放左手3,再放右手7,最后为3754261,牌序列从上到下为1624573。
import java.util.Scanner;
public class CMBC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//牌数
int k = sc.nextInt();//洗牌次数
int[] cards = new int[n];//牌序列
for (int i = 0; i < n; i++) {
cards[i] = sc.nextInt();
}
int[] leftHand = new int[n/2+n%2];//左手牌
int[] rightHand = new int[n/2];//右手牌
for (int i = 1; i <= k; i++) {
//分牌
System.arraycopy(cards, 0, leftHand, 0, leftHand.length);
System.arraycopy(cards, leftHand.length, rightHand, 0, rightHand.length);
//洗牌并合并
cards = shuffleCards(leftHand, rightHand, i);
}
for (int card : cards) {
System.out.print(card + " ");
}
}
private static int[] shuffleCards(int[] LH, int[] RH, int k) {
int[] res = new int[LH.length+RH.length];
int l = LH.length-1, r = RH.length-1;
int i = res.length-1;
if(k % 2 != 0){//奇数次洗牌
while (r >= 0){
res[i--] = RH[r--];
res[i--] = LH[l--];
}
}else {//偶数次洗牌
while (r >= 0){
res[i--] = LH[l--];
res[i--] = RH[r--];
}
}
//牌为奇数
if(l == 0){
res[0] = LH[0];
}
return res;
}
}