北理2017夏令营

在公司中,存在着领导-员工关系,一个领导可以有多个员工,一个员工只能有一个领导。用{员工,领导},{员工,领导},{员工,领导},……这样的格式录入数据,输出公司的管理关系。

  • 输入
    {21,13},{32,13},{24,14},{28,14},{13,11},{14,11}
  • 输出
    {11,[{13,[{21}{32}]}{14,[{24}{28}]}]}

其中同级员工要按照编号从小到大排列。


  1. 关于格式化输入,主要可用两种方法,C风格的可以用sscanf函数。例子是sscanf(str.c_str(),"{%d,%d}");。该函数的返回值是成功匹配的个数;C++风格就是字符流,16年已经总结过。
  2. 并查集常常用来处理集合之间的操作,用来寻找根节点也不错
#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);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值