Soldier and Cards
Description
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins thisfight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.
You have to calculate how many fights will happen and who will win the game, or state that game won't end.
Input
First line contains a single integer n (2 ≤ n ≤ 10), the number of cards.
Second line contains integer k1 (1 ≤ k1 ≤ n - 1), the number of the first soldier's cards. Then follow k1 integers that are the values on the first soldier's cards, from top to bottom of his stack.
Third line contains integer k2 (k1 + k2 = n), the number of the second soldier's cards. Then follow k2 integers that are the values on the second soldier's cards, from top to bottom of his stack.
All card values are different.
Output
If somebody wins in this game, print 2 integers where the first one stands for the number offights before end of game and the second one is1 or 2 showing which player has won.
If the game won't end and will continue forever output - 1.
Sample Input
4 2 1 3 2 4 2
6 2
3 1 2 2 1 3
-1
Sample Output
Hint
First sample:
Second sample:
题意:
游戏双方各有一些牌,牌上都有一个各不相同的值,每一轮取出最上面的牌进行比较,大的一方把对方的牌压在自己的一沓牌的下面,然后再把自己的这张牌再次压在最下面,就这样一直进行下去,直到有一方没有牌或者不会出现没有牌的情况为止。如果一直循环,输出-1,如果没有循环,输出游戏进行的次数和哪一方获胜。
思路:
定义两个队列,分别取出两个队列的队首,进行比较,如果q1的队首大于q2的队首,把q2的队首放在在q1队尾,然后再把q1的队首放在q1的队尾。如果q2的队首大于q1的队首,把q1的队首放在q2的队尾,然后把q2的队首放在q2的队尾。
代码:
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
queue<int>q1,q2;
int n,k1,k2,a;
while(scanf("%d",&n)!=EOF)
{
scanf("%d",&k1);
for(int i=0;i<k1;i++)
{
scanf("%d",&a);
q1.push(a);
}
scanf("%d",&k2);
for(int i=0;i<k2;i++)
{
scanf("%d",&a);
q2.push(a);
}
int ans=0;
while(1)
{
if(q1.empty()||q2.empty()) break;
int u=q1.front(),v=q2.front();
q1.pop();
q2.pop();
if(u>v)
{
q1.push(v);
q1.push(u);
}
else
{
q2.push(u);
q2.push(v);
}
ans++;
if(ans>1e6)
{
ans=-1;
break;
}
}
printf("%d",ans);
if(ans!=-1)
printf(" %d\n",q1.empty()?2:1);
}
return 0;
}