给一个字符串(aaaa(bbbb(cccc,dddd),eeee(ffff)))该字符串
表明的是各个人的层次关系。
比如aaaa是bbbb和eeee的领导,bbbb是cccc和dddd的领导。
现输入一个名称,比如ffff,要求输出其领导关系。
输出:aaaa>eeee>ffff
struct node { string name; int lead; }n[100];
,每个结点的lead值为其领导结点的索引值。#include
#include
#include
#include
#include
using namespace std;
struct node {
string name;
int lead;
}n[100];
void divide(string s,vector<string> &v,regex reg)
{
smatch mResult;
if (regex_search(s, mResult, reg)) {
for (auto it = mResult.prefix().first; it != mResult.prefix().second; it++) {
if (*it == ',')
continue;
v.push_back(string(1, *it));
}
v.push_back(string(mResult[0].first, mResult[0].second));
divide(mResult.suffix(), v, reg);
}
else {
for (auto it = s.begin(); it != s.end(); it++)
v.push_back(string(1, *it));
}
}
int main()
{
string source,people;
vector<string> mid;
cin >> source >> people;
regex reg("[a-zA-Z]+");
divide(source, mid, reg);
int lead = 0, i = 0;
stack<int> st;
for (auto it = mid.begin(); it != mid.end(); it++) {
//cout << *it << ' ';
if (*it == "(") {
st.push(lead);
lead = i;
}
else if (*it == ")") {
lead = st.top();
st.pop();
}
else {
i++;
n[i].name = *it;
n[i].lead = lead;
}
}
string p;
for (int j = 0; j <= i; j++) {
if (n[j].name == people) {
while (j != 0) {
p.insert(p.begin(),n[j].name.begin(),n[j].name.end());
if (n[j].lead != 0)
p.insert(p.begin(), '>');
j = n[j].lead;
}
break;
}
}
cout << p;
return 0;
}
(2020.4.12)
好吧时隔两个月,再看自己曾经的代码确实觉得emmmm,不过当时确实是想着学学regex才那么写
重新写了一个简单实用的
#include
#include
#include
#include
using namespace std;
string str;
map<string,string> mp; // <名字,领导名字>
stack<string> st; //栈顶永远是当前领导的名字
string last; //最后一个访问的同志,有可能是下一个领导
int getName(int i)
{
int start = i;
while(str[i]>='a' && str[i]<='z')
i++;
string name = str.substr(start,i-start);
mp[name] = st.top();
last = name; //记录
return i-1;
}
int main(){
cin >> str;
st.push(""); //第一个人没有领导
for(int i=0;i<str.length();i++){
if(str[i]>='a' && str[i]<='z')
i = getName(i);
else if(str[i] == '(') //见到左括号则说明换领导了
st.push(last); //最后遍历的那个人是当前领导
else if(str[i] == ')') //见到右括号则用栈还原上一个领导
st.pop();
}
string query, out;
cin >> query; //待查询人士
out = query;
query = mp[query];
while(query!=""){
out.insert(out.begin(),'>');
out.insert(out.begin(),query.begin(),query.end()); // out = query + out的高效版
query = mp[query];
}
cout << out << endl;
return 0;
}