HDU 4041 Eliminate Witches! (ACM ICPC 2011北京赛区网络赛)(二)

2014-11-23 22:08:39 ? 作者: ? 浏览: 12
1
wuzetian
3
nanoha
fate
hayate
1 2
2 3
3 2
2 1
Source
The 36th ACM/ICPC Asia Regional Beijing Site —— Online Contest
Recommend
lcy
题目大意:T组测试数据,接下来T组字符串,表示一棵树,从字符串看树的结构显而易见,然后输出这棵树访问的过程。
解题思路:模拟题,这题就是一种先序的方式,但是不是二叉树,所以自己写程序模拟一下过程就可以了
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxlen=10000010;
vector  ans;
vector  v;
map  mp;
char str[maxlen];
int len,num,pos;

void initial(){
	ans.clear();
	mp.clear();
	v.clear();
	num=1;
	pos=0;
}

void input(){
	scanf("%s",str);
	len=strlen(str);
}

void dfs(){
	if(pos>=len) return;
	string st;
	while(str[pos]>='a' && str[pos]<= 'z'){
		st.push_back(str[pos]);
		pos++;
	}
	ans.push_back(st);
	int now=num++;
	v.push_back(now);
	if(str[pos]=='('){
		pos++;
		dfs();
		v.push_back(now);
		while(str[pos]==','){
			pos++;
			dfs();
			v.push_back(now);
		}
		pos++;
	}else return;
}

void computing(){
	dfs();
}

void output(){
	printf("%d\n",num-1);
	for(int i=0;i>t;
	while(t-- >0){
		initial();
		input();
		computing();
		output();
	}
	return 0;
}

拓展:树的遍历方式(转载)
1)前序遍历
a)递归方式:
void preorder_recursive(Bitree T) /* 先序遍历二叉树的递归算法 */
{
if (T) {
visit(T); /* 访问当前结点 */
preorder_recursive(T->lchild); /* 访问左子树 */
preorder_recursive(T->rchild); /* 访问右子树 */
}
}
b)非递归方式
void preorder_nonrecursive(Bitree T) /* 先序遍历二叉树的非递归算法 */
{
initstack(S);
push(S,T); /* 根指针进栈 */
while(!stackempty(S)) {
while(gettop(S,p)&&p) { /* 向左走到尽头 */
visit(p); /* 每向前走一步都访问当前结点 */
push(S,p->lchild);
}
pop(S,p);
if(!stackempty(S)) { /* 向右走一步 */
pop(S,p);
push(S,p->rchild);
}
}
}
2)中序遍历
a)递归方式
void inorder_recursive(Bitree T) /* 中序遍历二叉树的递归算法 */
{
if (T) {
inorder_recursive(T->lchild); /* 访问左子树 */
visit(T); /* 访问当前结点 */
inorder_recursive(T->rchild); /* 访问右子树 */
}
}
b)非递归方式
void inorder_nonrecursive(Bitree T)
{
initstack(S); /* 初始化栈 */
push(S, T); /* 根指针入栈 */
while (!stackempty(S)) {
while (gettop(S, p) && p) /* 向左走到尽头 */
push(S, p->lchild);
pop(S, p); /* 空指针退栈 */
if (!stackempty(S)) {
pop(S, p);
visit(p); /* 访问当前结点 */
push(S, p->rchild); /* 向右走一步 */
}
}
}
3)后序遍历
a)递归方式
void postorder_recursive(Bitree T) /* 中序遍历二叉树的递归算法 */
{
if (T) {
postorder_recursive(T->lchild); /* 访问左子树 */
postorder_recursive(T->rchild); /* 访问右子树 */
visit(T); /* 访问当前结点 */
}
}
b)非递归方式
typedef str
-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: