思路:
首先是建树,通过指针建树,每次把建立的节点放到栈中,当下一次节点到达时,从栈中不断弹出元素,当找到一个节点的 . 比当前节点的少时,该节点即为当前节点的父节点。判断时根据输入,倒着判断。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<stack>
#include<vector>
using namespace std;
struct tree
{
string tag,name;
int floor;
tree* parent;
tree(int floor,string tag,string name)
{
this->floor=floor;
this->tag=tag;
this->name=name;
this->parent=0;
}
};
vector<tree*>nodes;
stack<tree*>sta;
vector<string>input;
vector<int>ans;
bool judge(const string &s,tree* t)
{
if(s[0]=='#')
return s==t->name;
else
{
if(s.size()!=t->tag.size()) return 0;
for(int i=0;i<s.size();i++)
if(tolower(s[i])!=tolower(t->tag[i]))
return 0;
return 1;
}
}
int main()
{
string tmp;
int n,m;
cin>>n>>m;
getchar();
for(int i=1;i<=n;i++)
{
string tag,name;
getline(cin,tmp);
int floor=0;
while(tmp[floor]=='.') floor++;
stringstream ss(tmp.substr(floor));
ss>>tag>>name;
tree*tmp_tree=new tree(floor,tag,name);
if(!sta.empty())
{
tree* top=sta.top();
while(top->floor>=floor)
{
sta.pop();
if(!sta.empty())
top=sta.top();
else break;
}
tmp_tree->parent=top;
}
sta.push(tmp_tree);
nodes.push_back(tmp_tree);
}
for(int k=1;k<=m;k++)
{
getline(cin,tmp);
input.clear();
string tmpp;
tmpp.clear();
for(int i=0;i<tmp.size();i++)
{
if(tmp[i]==' ')
{
input.push_back(tmpp);
tmpp.clear();
}
else tmpp+=tmp[i];
}
input.push_back(tmpp);
ans.clear();
for(int i=0;i<nodes.size();i++)
{
int pos=input.size()-1;
if(judge(input[pos],nodes[i]))
{
tree* t=nodes[i]->parent;
pos--;
while(t&&pos>=0)
{
if(judge(input[pos],t)) pos--;
t=t->parent;
}
if(pos==-1) ans.push_back(i+1);
}
}
printf("%d ",ans.size());
for(int i=0;i<ans.size();i++)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}