【题意】每个师傅可以有多个徒弟,由师傅和徒弟构建一棵完全二叉树如下:
给出多个玩家,输出他们的最近公共师傅。比如给出D J 最近公共师傅就是B
【输入】输入N为结点个数,接下来以层次遍历的方式给出N个结点。然后是X,表示X个玩家,接下来输入X个玩家
【输出】这X个玩家的最近公共师傅
【思路】从0开始给这个完全二叉树标号,则标号为j的结点,其师傅有(j-1)/2,循环,一直到结点0。 记录N个子节点的所有师傅(vector)father。然后遍历X个玩家的每个师傅,给每个师傅计数为 father_count,倒叙输出第一个father_count为X的师傅。就是他们的最近公共师傅
#include<iostream>
#include<cstring>
#include<vector>
#include<math.h>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
#define maxi 0x3f3f3f3f
std::vector<int> father[100000];//100000 nodes
int father_count[100000];
std::vector<string> nodes_name;
int main(int argc, char const *argv[])
{
int N;
cin>>N;
memset(father_count,0,sizeof(father_count));
for(int i=0;i<N;i++)
{
string str;
cin>>str;
nodes_name.push_back(str);// 从0开始的name
}
int j;
for(int i=1;i<N;i++)
{
j=i-1;
do{
j/=2;
father[i].push_back(j);
j--;
}while(j>=0);
}
int x;
cin>>x;
int t=x;
while(x--)
{
string str;
cin>>str;
int son;
for(int i=0;i<N;i++)
{
if(nodes_name[i]==str)
{
son=i;
break;
}
}
for(int i=0;i<father[son].size();i++)
{
father_count[father[son][i]]++;
}
}
for(int i=N-1;i>=0;i--)
{
if(father_count[i]>=t)
{
cout<<nodes_name[i]<<endl;
break;
}
}
return 0;
}