Game
Bob always plays game with Alice. Today, they are playing a game on a tree. Alice has m1 stones, Bob has m2 stones. At the beginning of the game, all the stones are placed on the nodes of a tree, except the root. Alice moves first and they take turns moving the stones. On each turn, the player chooses exactly ONE of his stones, moves this stone from current node to its parent node. During the game, any number of stones can be put on the same node.
The player who first moves all of his stones to the root of the tree is the loser. Assume that Bob and Alice are both clever enough. Given the initial positions of the stones, write a program to find the winner.
Input:
Input contains multiple test cases.
The first line of each test case contains three integers:n(1<n<=10), m1(1<=m1<=3), m2(1<=m2<=3), n is the number of nodes.
Next n-1 lines describe the tree. Each line contains two integers A and B in range [0,n), representing an edge of the tree and A is B’s parent. Node 0 is the root.
There are m1 integers and m2 integers on next two lines, representing the initial positions of Alice’s and Bob’s stones.
There is a blank line after each test case.
Output:
Output the winner’s name on a single line for each test case
Sample Input:
3 1 1
0 1
0 2
1
2
3 2 1
0 1
1 2
2 2
2
Sample Output:
Bob
Alice
#include <iostream>
#include <fstream>
using namespace std;
#define MAXN 10//图的最大结点数
int count1=0,count2=0;//记录石头的层数
int adj[MAXN][MAXN];//邻接矩阵,存储与该点相邻的结点
int visited[MAXN];
void dfs (int i,int position)//从顶点i出发进行遍历
{
int j;
visited[i]=1;//全局数组访问标记置1表示已经访问
count1++;
if(i==position)
{
count2=count1;
//dfs(j,position);
}
else
{
for(j=0; j<MAXN; j++)
{
if ((adj[i][j]==1)&&(!visited[j]))
{
dfs(j,position);
}
}
count1--;
}
}
void main()
{
//树节点总数 Alic的石头数 Bob的石头树
int stonetotalnum,alictotalnum,bobtotalnum;
int Alicstepnum=0,Bobstepnum=0;
int stoneposition;
ifstream stream("input.txt");
while(!stream.eof())
{
stream>>stonetotalnum>>alictotalnum>>bobtotalnum;
for (int i=1,x,y;i<=(stonetotalnum-1);i++)
{
stream>>x>>y;
adj[x][y]=1;//在邻接表中插入xy
adj[y][x]=1;//插入yx
}
for(int j=0;j<alictotalnum;j++)
{
stream>>stoneposition;
dfs(0,stoneposition);//从第0个顶点开始遍历整棵树,
//查找某块石头所在的层数
Alicstepnum+=(count2-1);
for(int k=0;k<MAXN;k++)
{
visited[k]=0;
}
count1=0;
count2=0;
}
for(int k=0;k<bobtotalnum;k++)
{
stream>>stoneposition;
dfs(0,stoneposition);//从第0个顶点开始遍历整棵树,
//查找某块石头所在的层数
Bobstepnum+=(count2-1);
for(int k=0;k<MAXN;k++)
{
visited[k]=0;
}
count1=0;
count2=0;
}
// cout<<Alicstepnum<<endl<<Bobstepnum<<endl;
if(Alicstepnum>Bobstepnum)
{
cout<<"Alice"<<endl;
}
else
{
cout<<"Bob"<<endl;
}
Alicstepnum=0;
Bobstepnum=0;
}
stream.close();
}