在做这一题时,一定要注意看清楚题目,要注意这一句话:
当轮到B出牌时,他的牌K与桌上的纸牌序列中的K相同,则把包括K在内的以及两个K之间的纸牌都赢回来,放入自己牌的队尾。注意:为了操作方便,放入牌的顺序是与桌上的顺序相反的。
牌桌上的牌在收回是,是倒叙的 ,就是因为没有看清楚这一点,debug了好久都没用,结果一看题目,才发现自己被坑呢!
import java.util.*;
public class Main extends Object {
private static final HashMap repeat = new HashMap<>();
public static void main(String[] args) {
Scanner cache = new Scanner(System.in);
String a = cache.next();
String b = cache.next();
ArrayList pai = new ArrayList<>();
ArrayList A = new ArrayList<>();
ArrayList B = new ArrayList<>();
char[] temp = a.toCharArray();
for (char c : temp) {
A.add(c);
}
temp = b.toCharArray();
for (char c : temp) {
B.add(c);
}
boolean flag = true;
int ok;
while (true) {
if (flag) {
char data1 = A.get(0);
chuPai(pai, A);
ok = doYouHava(pai, data1);
if (ok == -1) {
char data2 = B.get(0);
chuPai(pai, B);
ok = doYouHava(pai, data2);
if (ok != -1) {
shouPai(pai, B, ok, A, B);
flag = false;
}
} else {
shouPai(pai, A, ok, A, B);
flag = true;
}
} else {
char data1 = B.get(0);
chuPai(pai, B);
ok = doYouHava(pai, data1);
if (ok == -1) {
char data2 = A.get(0);
chuPai(pai, A);
ok = doYouHava(pai, data2);
if (ok != -1) {
shouPai(pai, A, ok, A, B);
flag = true;
}
} else {
shouPai(pai, B, ok, A, B);
flag = false;
}
}
if (A.size() == 0) {
break;
}
if (B.size() == 0) {
break;
}
}
if (A.size() != 0) {
for (int x = 0; x < A.size(); x++) {
System.out.print(A.get(x));
}
} else {
for (int x = 0; x < B.size(); x++) {
System.out.print(B.get(x));
}
}
cache.close();
System.exit(0);
}
public static void shouPai(ArrayList pai, ArrayList temp, int index, ArrayList A,
ArrayList B) {
// 判断有没有陷入死循环
String sum = new String();
sum += String.valueOf(A) + " ";
sum += String.valueOf(B) + " ";
sum += String.valueOf(pai);
if (repeat.get(sum) != null) {
System.out.println(-1);
System.exit(0);
} else {
repeat.put(sum, sum);
}
// 将倒叙牌收入
for (int x = (pai.size() - 1); x >= index; x--) {
char data = pai.get(x);
temp.add(data);
}
int length = pai.size();
for (int x = index; x < length; x++) {
pai.remove(pai.size() - 1);
}
}
// 判断前面有没有重复的
public static int doYouHava(ArrayList pai, char temp) {
for (int x = 0; x < pai.size() - 1; x++) {
if (pai.get(x).equals(temp)) {
return x;
}
}
return -1;
}
// 玩家出牌
public static void chuPai(ArrayList pai, ArrayList temp) {
char data = temp.get(0);
pai.add(data);
temp.remove(0);
}
}