解题思路
设置一个结构体node,记录label和id
还有级数
封装一个tolow函数,用于把字母化成小写
封装一个split函数,把输入的给拆分成node
详情看代码
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct node{
string label,id;
int level;
};
node ele[105];
vector<string> input; //输入的查询
vector<int> output; //输出
void tolow(string &str)
{
for(int i=0;i<str.size();i++)
{
if(isalpha(str[i])) str[i]=tolower(str[i]);
}
}
void split(int j,string str)
{
int p_n=0,flag=0,index1=0,index2=0,index3=0,flag1=0;
if(str.find('#') == string::npos) //没有#
flag1=1;
for(int i=0;i<str.size();i++)
{
if(str[i]=='.') p_n++;
if(str[i]!='.'&&flag==0) {flag++,index1=i;}
if(str[i]=='#') index3=i;
}
string label,id;
ele[j].level=p_n/2;
if(flag1==1){
label = str.substr(index1);
tolow(label);
ele[j].label=label;
}
else
{
label = str.substr(index1,index3-index1-1);
tolow(label);
ele[j].label=label;
ele[j].id = str.substr(index3);
}
}
string temp;
int main()
{
cin>>n>>m;
getchar();
for(int i=0;i<n;i++)
{
getline(cin,temp);
split(i,temp);
}
// for(int i=0;i<n;i++)
// cout<<ele[i].level<<" "<<ele[i].label<<" "<<ele[i].id<<endl;
for(int i=0;i<m;i++)
{
getline(cin,temp);
// cout<<"搜索"<<temp<<endl;
stringstream s;
s<<temp;
string t;
while(s>>t){
if(t[0]!='#') tolow(t);
input.push_back(t);
}
int size=input.size();
for(int k=0;k<n;k++)
{
if((input[size-1][0]=='#'&&input[size-1]==ele[k].id)||
(input[size-1][0]!='#'&&input[size-1]==ele[k].label)) {
if(size==1) output.push_back(k+1); //普通查询
else { //多级
//从这个node 往上遍历,查找是否满足要求
int line=k-1,lev=ele[k].level;
int ts=size-2;
for(int h=line;h>=0;h--)
{
if(ele[h].level<lev)
{
if(input[ts][0]!='#'&&input[ts]==ele[h].label) ts--;
else if(input[ts][0]=='#'&&input[ts]==ele[h].id) ts--;
if(ts<0) {output.push_back(k+1);break;}
}
}
}
}
}
cout<<output.size();
for(int i=0;i<output.size();i++) cout<<" "<<output[i];
cout<<endl;
input.clear();
output.clear();
}
return 0;
}
/*
11 5
html
..head
....title
..body
....h1
....p #subtitle
....div #main
......h2
......p #none
......div
........p #two
p
#subtitle
h3
div p
div div p
*/