sicily 1034之思路清晰

来源:互联网 发布:vs2015能开发php吗 编辑:程序博客网 时间:2024/05/02 02:34

题目在这里1034

这道题是图的遍历。只是这个图是个“森林”,就是有多颗树。但是在遍历之前需要进行判断,因为这些树有些是无效的,测试用例中会出现环和指向同一个节点的两条边。在输入参数的时候就可以对这些特殊情况进行判断,如果其有问题,则不进行遍历,直接输出“INVALID”。仅仅对有效地输入森林进行遍历。

这道题只要对这些边界条件思考清楚,很容易AC,下面是我的代码,仅供参考

#include<iostream>#include<vector>#include<cstring>using namespace std;struct Node{int _id;int _depth;Node(int id){this->_id = id;this->_depth = 0;}};int from[101], to[101], depth, width;vector<Node> forest[101];bool visited[101];void dfs(int start, int d){visited[start] = true;if (d > depth)depth = d;for (vector<Node>::iterator iter = forest[start].begin(); iter != forest[start].end(); iter++){if (visited[iter->_id] == false){iter->_depth = d + 1;dfs(iter->_id, iter->_depth);}}return;}bool calc(){bool noRoot = true;//找根for (int i = 0; i < 101; i++){if (from[i] != 0 && to[i] == 0){noRoot = false;dfs(i, 0);}}if (noRoot)return false;//森林没有根,说明有环else{for (int i = 1; i < 101; i++){if (to[i] != 0 && visited[i] == false)//森林有根,但是有些树没有被访问过,说明这些树是无效的、有环的树return false;}return true;}}int calc_width(){int level[101] = { 0 }, count = 0, re = 0;for (int i = 0; i < 101; i++){for (vector<Node>::iterator iter = forest[i].begin(); iter != forest[i].end(); iter++){count++;level[iter->_depth]++;if (re < level[iter->_depth])re = level[iter->_depth];}}return width - count > re ? width - count : re;//width - count表示深度是0的节点数,即根的节点数,因为在添加的时候,这些匿名的根没有加到forest里面}int main(){int n, m, fr, too;bool valid;while (cin >> n >> m && n != 0){valid = true;memset(from, 0, sizeof(from));memset(to, 0, sizeof(to));memset(visited, false, sizeof(visited));depth = 0;width = n;for (int i = 0; i < 101; i++){forest[i].clear();}for (int i = 0; i < m; i++){cin >> fr >> too;from[fr]++;to[too]++;//检查有没有指向同一个节点的两条边if (to[too] > 1)valid = false;elseforest[fr].push_back(Node(too));}if (!valid){cout << "INVALID" << endl;continue;}if (m == 0){width = calc_width();cout << depth << " " << width << endl;continue;}valid = calc();if (!valid){cout << "INVALID" << endl;}else{width = calc_width();cout << depth << " " << width << endl;}}//system("pause");return 0;}


0 0
原创粉丝点击