小米2017校园招聘编程题

来源:互联网 发布:linux5.5 yum安装lnmp 编辑:程序博客网 时间:2024/04/27 15:55

题目:



代码:

#include<iostream>  #include<vector>  #include<map>  #include<sstream>  #include<fstream>  #include<set>#include<algorithm>  using namespace std;int total_level = 0;void BFS(int root,vector<vector<int>>&data,int level){for (int i = 0; i < data[root].size();i++){int new_root = data[root][i];int new_level = level + 1;if (new_level>total_level)total_level = new_level;BFS(new_root, data, new_level);}}void find_root(vector<vector<int>>&data, int num, int row,vector<int>node){int re = 0,root,total=0;int size = node.size();int max = *(--node.end());vector<int>::iterator iter;vector<int>flag(size, 1);for (int i = 0; i < max; i++){if (data[i].size() != 0){for (int j = 0; j < data[i].size(); j++){iter = find(node.begin(), node.end(), data[i][j]);if (iter != node.end()){*iter = -1;}}}}//寻找根节点for (int i = 0; i < node.size(); i++)if (node[i] != -1)root = node[i];total = 0;BFS(root,data,1);}int main(){ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");string str;int size, root, temp;int num, son;int node, row;vector<int>nodes;vector<int>tmp;vector<vector<int>>data;stringstream mystream;int count = 0;for (int i = 0; i < 1001; i++)data.push_back(tmp);while (fin >> num){row = 0;while (fin >> root >> son){data[root].push_back(son);row++;if(find(nodes.begin(),nodes.end(),root)==nodes.end())nodes.push_back(root);if (find(nodes.begin(), nodes.end(), son) == nodes.end())nodes.push_back(son);}}total_level = 0;find_root(data, num, row, nodes);cout << total_level << endl;}


测试用例1:

5
1 2
2 3
3 4
4 5

结果:

测试用例2:

2

1 2

结果:

测试用例3:



算法思想:

因为树的编号最大值为999,所以新建一个容器的容器,我们将编号为n的根结点的所有子节点存放在二维容器的第n个元素里,所以在BFS深度搜索的时候就可以直接

data[root]寻找到它的所有根结点,然后利用深度优先搜索的方法递归回溯。题目不难!!!!!

0 0
原创粉丝点击