试题编号:201809-3
试题名称:元素选择器
时间限制:1.0s
内存限制:256.0MB
问题描述:
题目唯一需要注意的坑就是,需要连续的缩进才是前面元素的后代,所以应该是树的结构(但我还是用的数组来做),想到这一点就没问题了。
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<ctype.h>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
struct element{
int no;
string label;
string id;
};
struct review{
string last;
int start;
int level;
};
stack<review>r;
vector<element>v;
int main(){
int n,m,num=0;
char c;
scanf("%d %d",&n,&m);
getchar();
//用vector结构体存储输入数据,no存储等级,label存储标签,id存储id
for(int i=0;i<n;i++){
int tno=0;
char tc;
string tid="",tlabel="";
element temp;
while((c=getchar())!='\n'){
int flag=1;
if(c=='.'){
tno++;
}else if(c=='#'){
cin>>tid;
getchar();
temp.id=c+tid;
break;
}else{
tlabel+=c;
while((tc=getchar())!=' '){
if(tc=='\n'){//本该被c读入的'\n'被tc读入,用flag来结束此次读入
flag=0;
break;
}
tlabel+=tc;
}
temp.label=tlabel;
if(!flag)
break;
}
}
temp.no=tno/2;
v.push_back(temp);
num++;
}
//命令处理
while(m--){
deque<string>cmd;
queue<int>ans;
review temp;
temp.last="";
temp.level=-1;
temp.start=0;
r.push(temp);
char s[81];
char *p;
cin.getline(s,81);
p=strtok(s," ");
while(p){
cmd.push_back(p);
p=strtok(NULL," ");
}
while(!cmd.empty()){
int flag=0;
string ts;
ts=cmd.front();
cmd.pop_front();
for(int i=r.top().start;i<num;i++){
if(v[i].no<=r.top().level){
flag=1;
cmd.push_front(ts);
cmd.push_front(r.top().last);
r.pop();
r.top().start=i;
break;
}
if((ts==v[i].id||(stricmp(ts.c_str(),v[i].label.c_str())==0))&&(v[i].no>r.top().level)){
flag=1;
if(!cmd.empty()){
temp.start=i+1;
temp.level=v[i].no;
temp.last=ts;
r.push(temp);
break;
}else{
for(int j=i;j<num;j++){
if((ts==v[j].id||(stricmp(ts.c_str(),v[j].label.c_str())==0))&&(v[j].no>r.top().level)){
ans.push(j);
}
}
break;
}
}
}
if(!flag)
break;
}
printf("%d ",ans.size());
while(!ans.empty()){
int t=ans.front();
ans.pop();
printf("%d ",t+1);
}
printf("\n");
}
}
/*
11 5
html
..head
....title
..body
....h1
....p #subtitle
....div #main
......h2
......p #one
......div
........p #two
div p
div div p
head title h2
head title body
html head body h1
*/