We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Basic imperative approach that handles all test cases:
#include<cmath>#include<cstdio>#include<vector>#include<iostream>#include<algorithm>#include<map>#include<regex>#include<sstream>usingnamespacestd;intmain(){// number of tag and query linesintN,Q;scanf("%d %d\n",&N,&Q);// names and logic for parsing data// ================================// stack object for parsing documentvector<string>tag_stack;// parsing sentinalsstringendtag_sentinal="/";// container for fully qualified attributesmap<string,map<string,string>>document_map;// accumulate information from the documentstringtag;for(inti=0;i<N;i++){// read in a tag linegetline(cin,tag);// strip the < and >tag=tag.substr(1);tag.pop_back();// initialize tag's streamstringstreamtag_stream;tag_stream<<tag;// pop tag stack if endtagif(tag.substr(0,1)==endtag_sentinal){tag_stack.pop_back();continue;}// otherwise push onto tag stackelse{tag.clear();tag_stream>>tag;tag_stack.push_back(tag);}// move on if not attributes or handle themif(tag_stream.eof())continue;// initialize attribute mapmap<string,string>attributes;// extract and format attribute keys and valuesstringkey,equal_operator,value;while(!tag_stream.eof()){tag_stream>>key>>equal_operator>>value;value=value.substr(1);value.pop_back();attributes.insert(pair<string,string>(key,value));}// update document map with a new key-value pairstringstreamkey_path;for(string&t:tag_stack){key_path<<t;if(t!=tag)key_path<<".";}document_map.insert(pair<string,map<string,string>>(key_path.str(),attributes));}// names and logic for parsing queries// ===================================// query parsing regular expressionregexquery_regex("([a-zA-Z0-9\\.]+)~([_a-zA-Z0-9]+)");// answer queriesstringquery;for(inti=0;i<Q;i++){// print not found if no documentif(document_map.size()==0){cout<<"Not Found!"<<endl;continue;}// read the querygetline(cin,query);// initialize regex match containersmatchquery_smatch;// exit if no match at allif(!regex_match(query,query_smatch,query_regex)){return-1;}// print not found if query not in documentif(document_map.find(query_smatch[1])==document_map.end()){cout<<"Not Found!"<<endl;continue;}// print not found if no attributesif(document_map[query_smatch[1]].size()==0){cout<<"Not Found!"<<endl;continue;}// print not found if no attribute or print attributeautoptr=document_map[query_smatch[1]].find(query_smatch[2]);if(ptr==document_map[query_smatch[1]].end())cout<<"Not Found!"<<endl;elsecout<<ptr->second<<endl;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Attribute Parser
You are viewing a single comment's thread. Return to all comments →
Basic imperative approach that handles all test cases: