uva 122 Trees on the level

来源:互联网 发布:腾讯何时优化吃鸡 编辑:程序博客网 时间:2024/04/30 21:53

题目要求按层次输出数的各个节点,其实只要对输入的数据做个排序就可以了。

#include <iostream>using namespace std;#include <string>#include <set>#include <algorithm>struct Node {string v;string path;};Node nodes[300];set<string> v_set;set<string> p_set;int get_(string s) {int i=0;for (i=0;i<s.length();i++) if (s[i]==',')return i;return -1;}bool cmp(const Node& a, const Node& b) {if (a.path.length()!=b.path.length())return a.path.length()<b.path.length();return a.path<b.path;}int main() {int flag;int i,j,k;string str;i=0;flag=1;v_set.clear();p_set.clear();while (cin >> str) {if (str!="()") {j=get_(str);if (j!=-1) {nodes[i].v=str.substr(1,j-1);nodes[i].path=str.substr(j+1, str.length()-j-2);if (nodes[i].v.length()==0)flag=0;if (p_set.find(nodes[i].path)!=p_set.end())flag=0;elsep_set.insert(nodes[i].path);i++;}}else {if (flag==0)cout << "not complete\n";else {sort(nodes, nodes+i, cmp);p_set.clear();if (nodes[0].path.length()==0) {p_set.insert(nodes[0].path);for (j=1;j<i;j++) {if (p_set.find(nodes[j].path.substr(0,nodes[j].path.length()-1))==p_set.end())flag=0;elsep_set.insert(nodes[j].path);}if (flag==0)cout << "not complete\n";else {for (j=0;j<i-1;j++)cout << nodes[j].v << " ";cout << nodes[j].v << endl;}}elsecout << "not complete\n";}i=0;p_set.clear();v_set.clear();flag=1;}}return 0;}