在公司中,存在着领导-员工关系,一个领导可以有多个员工,一个员工只能有一个领导。用{员工,领导},{员工,领导},{员工,领导},……这样的格式录入数据,输出公司的管理关系。
- 输入
{21,13},{32,13},{24,14},{28,14},{13,11},{14,11}
- 输出
{11,[{13,[{21}{32}]}{14,[{24}{28}]}]}
其中同级员工要按照编号从小到大排列。
- 关于格式化输入,主要可用两种方法,C风格的可以用
sscanf
函数。例子是sscanf(str.c_str(),"{%d,%d}");
。该函数的返回值是成功匹配的个数;C++风格就是字符流,16年已经总结过。 - 并查集常常用来处理集合之间的操作,用来寻找根节点也不错
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
#include<sstream>
using namespace std;
int father[100];
int num;
string source; //{21,13},{32,13},{24,14},{28,14},{13,11},{14,11}
map<int, vector<int> > relation; // <父亲,儿子们>
string getPair(string str)
{
istringstream in(str);
char t;
int n1, n2;
in >> t >> n1 >> t >> n2 >> t;
relation[n2].push_back(n1);
father[n1] = n2;
num = n1; //随便保存一个数,后面用这个数来找根
string res;
in >> res;
if (res[0] == ',')
res = res.substr(1);
return res;
}
void dfs(int r)
{
cout << "{" << r;
if (relation[r].size() != 0) {
cout << ",[";
sort(relation[r].begin(), relation[r].end());
for (auto it = relation[r].begin(); it != relation[r].end(); it++)
dfs(*it); //遍历所有儿子
cout << ']';
}
cout << "}";
}
int main()
{
for (int i = 0; i < 100; i++) //并查集的思想,利用father数组可以快速找到根节点
father[i] = i;
getline(cin, source);
while (source.length() != 0) { //循环到删空为止
source = getPair(source);
}
int root = num;
while (father[root] != root)
root = father[root]; //找到根节点
dfs(root);
}