1. 程式人生 > >CCF 201809-3 元素選擇器

CCF 201809-3 元素選擇器

試題編號: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 */