欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UVa712 S-Trees满二叉树

程序员文章站 2021-12-23 21:07:30
...

题目意思就是给你一个满二叉树,然后输入命令查询,0是向左,1是向右。比较简单,直接上代码。

#include<iostream>
#include <string>
#include <string.h>
using namespace std;

int lefttree[1000],righttree[1000]; int n;
string st; int countindex = 0; int xn[1000]; int a[1000]; int zeroOrone = 0; char console[1000]; int kase = 0;
int square(int v, int c) {
	int sum = 1;
	for (int i = 0; i < c; i++) {
		sum = sum * v;
	}
	return sum;
}
void readInput(int n) {
	memset(lefttree, 0, sizeof(lefttree));
	memset(righttree, 0, sizeof(righttree));
	countindex = 0;
	char s[3];
	for (int i = 0; i < n; i++) {
		cin >> s;
		xn[i] = s[1]-'0';
	}
	cin >> st;
	for (int i = 1; i <= square(2,n-1)-1; i++) {
		lefttree[i] = i * 2;
		righttree[i] = i * 2 + 1;
	}
	
}
void getvalue(int u){
		int leftindex0 = lefttree[u];
		int rightindex0 = righttree[u];
		if (leftindex0 == 0&&rightindex0== 0) {
			lefttree[u] = st[countindex++]-'0'; righttree[u]=st[countindex++]-'0';
			return;
		}
		getvalue(leftindex0);
		getvalue(rightindex0);
}
bool isflag = false;
void treeFindOrder(int u,int c) {
	if (c == -1&&!isflag) {
		zeroOrone = u; 
		isflag = true;
		return;
	}
	if(a[c]==0){ 
		int leftindex0 = lefttree[u]; treeFindOrder(leftindex0, --c);
	}
	if (a[c] == 1) {
		int rightindex0 = righttree[u]; treeFindOrder(rightindex0, --c);
	}
}
void getorder() {
	int d; string s;
	cin >> d;
	for (int i = 0; i < d; i++) {
		cin >> s;
		for (int i = 0; i < n; i++) {
			a[n-1-i] = s[xn[i]-1]-'0';
		}
		//遍历树
		isflag = false;
		treeFindOrder(1, n - 1);
		char xr = zeroOrone + '0';
		console[i] = xr;
	}
	printf("S-Tree #%d:\n", kase);
	for(int i=0;i<d;i++)
	cout << console[i];
	cout << endl<<endl;
}
int main()
{
   while (cin >> n && n) {
	kase++;
	readInput(n);
	getvalue(1);
	getorder();
   }
	return 0;
}

 

相关标签: 算法