小猫钓鱼问题:
描述:初始,两个人各有n张牌(牌面0-10),顺序固定,只能按顺序出牌。然后,两个人轮流在桌面上以接龙的方式出牌,当某个人放置的牌在桌面上已经出现时,他收起相同牌面及其中间的牌作为自己的筹码,同时需要再放一张牌到桌面。某人手上的牌出完后,另一个人继续出,直到两人手上都没牌为止,输出结束时两个人手上的筹码数。
#include<iostream>
using namespace std;
struct queue {
int head; //队列首
int tail; //队列尾
int data[100];
};
struct stack {
int data[100];
int top; //栈顶
};
int main() {
int res1 = 0, res2 = 0;
queue q1, q2;
stack s;
int n;
int book[11]; //记录桌上是否有某张牌
q1.head = q1.tail = 1;
q2.head = q2.tail = 1;
s.top = 1; //初始化
for (int i = 1; i <= 10; ++i) {
book[i] = 0; //为0说明桌上没有这张牌 i就是牌面
}
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> q1.data[q1.tail];
++q1.tail;
}
for (int i = 1; i <= n; ++i) {
cin >> q2.data[q2.tail];
++q2.tail;
}
while (q1.head < q1.tail || q2.head < q2.tail) {
loop:if (q1.head < q1.tail) {
int t = q1.data[q1.head];
if (book[t] == 0) { //桌面没这张牌
q1.head++; //出牌
s.data[s.top] = t;
s.top++; //桌上多了一张牌
book[t] = 1;
}
else { //桌上有这张牌
q1.head++;
++res1; //当前这张牌直接进筹码
while ((s.data[--s.top]) != t) {
++res1;
book[s.data[s.top]] = 0;
}
book[s.data[s.top]] = 0; //最后一张牌进筹码
++res1;
book[s.data[s.top]] = 0;
goto loop;
}
}
loop2:if (q2.head < q2.tail) {
int t = q2.data[q2.head];
if (book[t] == 0) { //桌面没这张牌
q2.head++; //出牌
s.data[s.top] = t;
s.top++; //桌上多了一张牌
book[t] = 1;
}
else { //桌上有这张牌
q2.head++;
++res2; //当前这张牌直接进筹码
while ((s.data[--s.top]) != t) {
++res2;
book[s.data[s.top]] = 0;
}
book[s.data[s.top]] = 0; //最后一张牌进筹码
++res2;
book[s.data[s.top]] = 0;
goto loop2;
}
}
}
cout << res1 << " " << res2;
system("pause");
return 0;
}