九度1090-路径打印-多叉树

这道题真的是巨坑!调了将近一个小时的格式才发现要按照前面父目录的字符串长度进行缩进


附上PE6发之后好不容易AC的代码:

#include<bits/stdc++.h>
using namespace std;//多叉树 
typedef struct Node{
	char s[60];
	Node *son;
	Node *next_sibling;
}Node;
Node node[30]; 

void DFS(Node *root, int depth)
{
	Node *p = root->son;
	while(p)
	{
		for(int i = 1; i <= depth; i++)
		{
			cout << " "; 
		}
		int len = strlen(p->s);
		cout << p->s << endl;
		DFS(p, depth+1+len);//这里输出格式一定要注意!!
		p = p->next_sibling;
	}
}

int main()
{
	int n;
	while(~scanf("%d", &n) && n)
	{
		Node *rt = new Node();
		rt->son = NULL;
		rt->next_sibling = NULL;
		while(n--)
		{
			char s[60];
			scanf("%s", s);
			int len = strlen(s);
			char tmp[60];
			memset(tmp, 0, sizeof(tmp));
			int flag = 0;
			Node *p = rt;
			for(int i = 0; i <= len-1; i++)
			{
				if(s[i] != '\\')
				{
					tmp[flag++] = s[i];
				}
				if(s[i] == '\\' || i == len-1)
				{
					if(p->son == NULL)
					{
						Node *tt = new Node();
						strncpy(tt->s, tmp, flag);
						tt->son = NULL;
						tt->next_sibling = NULL;
						p->son = tt;
						p = tt;
					}
					else
					{
						Node *pre = p;
						p = p->son;
						while(p && strcmp(p->s, tmp) < 0)
						{
							//printf("%s %s\n", p->s, tmp);
							pre = p;
							p = p->next_sibling;
						}
						if(p == NULL)
						{
							Node *tt = new Node();
						    strncpy(tt->s, tmp, flag);
						    tt->son = NULL;
						    tt->next_sibling = NULL;
						    pre->next_sibling = tt;
						    p = tt;
						    //printf("aa\n");
						}
						else if(strcmp(p->s, tmp) > 0)
						{
							Node *tt = new Node();
						    strncpy(tt->s, tmp, flag);
						    tt->son = NULL;
						    tt->next_sibling = p;
						    if(p == pre->son)
						       pre->son = tt;
						    else if(p == pre->next_sibling)
						       pre->next_sibling = tt;
						    p = tt;
						}
					    //等于节点值的只需要找到这个节点 
					}
					memset(tmp, 0, sizeof(tmp));
					flag = 0;
				}
				//printf("i:%d s[i]:%c\n", i, s[i]);
			}
		}
		DFS(rt, 0);
		cout << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值