试题编号: 201809-3
试题名称: 元素选择器
时间限制: 1.0s
内存限制: 256.0MB
80分代码(个人认为这才是正解,感觉测试数据不严谨)
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<sstream>
using namespace std;
const int N = 105;
stringstream sstream;
vector<string>ss;
vector<int>ans;
struct Node {
string label, id;
int cnt, parent;
}nodes[N];
void Lower(string& s)
{
for (int i = 0; i < s.length(); i++) s[i] = tolower(s[i]);
}
void dfs(int cnt, int index, Node node) {
if (cnt == ss.size()) {
ans.push_back(index);
return;
}
if (node.parent == -1) return;
string cmpstr = ss[ss.size() - 1 - cnt];
if (node.id == cmpstr || node.label == cmpstr) dfs(cnt + 1, index, nodes[node.parent]);
}
int main()
{
int n, m;
string s;
cin >> n >> m;//读入n和m
getchar();//读取换行符
for (int i = 1; i <= n; i++)
{
int cnt = 0;
sstream.clear();
getline(cin, s);
while (s[cnt] == '.') cnt++;
sstream.str(s.substr(cnt));
sstream >> nodes[i].label >> nodes[i].id;
Lower(nodes[i].label);//由于标签属性大小写不敏感,因此统一换成小写
for (int j = i - 1; j >= 1; j--) {
if (nodes[j].cnt == cnt / 2 - 1) {
nodes[i].parent = j;
break;
}
}
nodes[i].cnt = cnt / 2;
}
for (int i = 0; i < m; i++)//读入m个查询
{
ans.clear();
ss.clear();
string temp;
stringstream sstream;
getline(cin, s);
sstream.str(s);
while (sstream >> temp) if (temp != "")ss.push_back(temp);
int len = ss.size();
for (int j = 0; j < len; j++)//将标签统一化成小写
if (ss[j][0] != '#') Lower(ss[j]);
for (int j = 1; j <= n; j++) dfs(0, j, nodes[j]);
cout << ans.size();
for (int j = 0; j < ans.size(); j++) cout << " " << ans[j];
cout << endl;
}
return 0;
}
100分代码
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<sstream>
using namespace std;
const int N = 105;
int n, m;
string s;
stringstream sstream;
vector<string>ss;
set<int>ans;
struct Node {
string label, id;
int level;
}nodes[N];
void Lower(string& s)
{
for (int i = 0; i < s.length(); i++) s[i] = tolower(s[i]);
}
void dfs(int cnt, int fatherlevel, int now) {
if (cnt == ss.size()) {
ans.insert(now);
return;
}
if (now == n) return;
for (int j = now; j < n; j++) {
Node node = nodes[j];
if (nodes[j].level <= fatherlevel) return;
string cmpstr = ss[cnt];
if (nodes[j].label == cmpstr || nodes[j].id == cmpstr) dfs(cnt + 1, nodes[j].level, j + 1);
}
}
int main()
{
cin >> n >> m;
getchar();//读取换行符
for (int i = 0; i < n; i++)
{
int cnt = 0;
sstream.clear();
getline(cin, s);
while (s[cnt] == '.') cnt++;
sstream.str(s.substr(cnt));
sstream >> nodes[i].label >> nodes[i].id;
Lower(nodes[i].label);
nodes[i].level = cnt/2;
}
for (int i = 0; i < m; i++)
{
ans.clear();
ss.clear();
string temp;
stringstream sstream;
getline(cin, s);
sstream.str(s);
while (sstream >> temp)if (temp != "")ss.push_back(temp);
int len = ss.size();
for (int j = 0; j < len; j++)
if (ss[j][0] != '#') Lower(ss[j]);
dfs(0, -1, 0);
cout << ans.size();
for (set<int>::iterator it = ans.begin(); it != ans.end(); ++it) cout << " " << *it;
cout << endl;
}
return 0;
}