#Description
给你一棵二叉树,输入
多说无益,看输入
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
要求输出
5 4 8 11 13 4 7 2 1
not complete
看图
11是左边左边 所以LL
7是左边左边左边 所以LLL
5没有,所以旁边是空的
然后横着输出
#Algorithm
先字符串处理下 把括号里面的数和字符串提取出来
如
11 LL
7 LLL
8 R
这样的,然后针对字符串排序就好了
排序规则是 长度小的在前面
长度一样L在前 因为 L的字典序本来就比R小,所以直接比字典序就好了
排序好了输出就是了
当然了 还有 not complete的情况
如果残缺了就不行
找残缺也很容易
比如 现在有 LLR
那么一定要有LL才行,没有LL那就残缺了
当然了 重复也不行 比如两个LLR LLR,那么也是有问题的
我为了练习STL用了set 和 map做
set可以直接通过结构体重写小于号来排序
map可以拿字符串当下标(应该叫做键更为妥当)
当然了
根本没必要这么做
直接数组存
然后sort一下
有重复的因为sort了扫一遍就出来了
找前缀也就是o(n ^ 2)就得到
#Code
#include <cstdio>
#include <iostream>
#include <sstream>
#include <set>
#include <map>
using namespace std;
string s;
struct V
{
int n;
string s;
V(){}
V(const int &n, const string &s) : n(n), s(s){}
bool operator < (const V v) const
{
if (s.size() < v.s.size() || (s.size() == v.s.size() && s < v.s)) return true;
return false;
}
};
int n;
const int maxn = 256 + 9;
V a[maxn];
set<V> myset;
map<string, int> mymap;
int main()
{
// freopen("input.txt", "r", stdin);
while (cin >> s)
{
if (s == "()")
{
set<V>::iterator it;
bool flag = true;
for (it = myset.begin(); it != myset.end(); it++)
{
string its = (*it).s;
if (mymap[its] > 1)
{
flag = false;
break;
}
string prefix = its.substr(0, its.size() - 1);
if (mymap[prefix] == 0)
{
flag = false;
break;
}
}
if (flag)
{
it = myset.begin();
cout << (*it).n;
it++;
for (; it != myset.end(); it++)
cout << ' ' << (*it).n;
cout << endl;
}else
cout << "not complete" << endl;
myset.clear();
mymap.clear();
continue;
}
int p = s.find(',');
string sn = s.substr(1, p - 1);
stringstream ss(sn);
int vn;
ss >> vn;
string vs = s.substr(p + 1, s.size() - p - 2);
myset.insert(V(vn, vs));
mymap[vs]++;
}
}