[UVA] Trees on the level

题目:https://vjudge.net/problem/UVA-122

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>

#pragma warning(disable:4996)
using namespace std;
const int maxn = 550;
const int root = 1;
int cnt, left[maxn], right[maxn], value[maxn];
bool failed, have_value[maxn];
char s[maxn];
vector<int> res;
void new_tree() {
	left[root] = right[root] = 0;
	have_value[root] = false;
	cnt = root;
	return;
}
int newnode() {
	int u = ++cnt;
	left[u] = right[u] = 0;
	have_value[u] = false;
	return u;
}
void addnode(int v, char* s) {
	int n = (int)strlen(s);
	int u = root;
	for (int i = 0; i < n; i++)
		if (s[i] == 'L') {
			if (!left[u]) left[u] = newnode();
			u = left[u];
		}
		else if (s[i] == 'R') {
			if (!right[u]) right[u] = newnode();
			u = right[u];
		}
	if (have_value[u]) failed = true;
	value[u] = v;
	have_value[u] = true;
	return;
}
bool read_input() {
	failed = false;
	while(1) {
		if (scanf("%s", s) != 1) return false;
		if (!strcmp(s, "()")) break;
		int v;
		sscanf(&s[1], "%d", &v);
		addnode(v, strchr(s, ',') + 1);
	}
	return true;
}
bool bfs() {
	if (failed) return false;
	queue<int>q;
	res.clear();
	q.push(root);
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		if (!have_value[u]) return false;
		a.push_back(value[u]);
		if (left[u]) q.push(left[u]);
		if (right[u]) q.push(right[u]);
	}
	return true;
}

void print() {
	for (int i = 0; i < res.size(); i++) {
		if (i) printf(" ");
		printf("%d", res[i]);
	}
	printf("\n");
	return;
}

int main() {
	while (1) {
		new_tree();
		if (!read_input()) break;
		if (!bfs()) failed = true;
		if (failed) printf("not complete\n");
		else print();
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值