ACM-ICPC国际大学生程序设计竞赛北京赛区(2016)网络赛 A

字典树 + dfs

题解:

题意: 有nn本书, 每本书的格式为CATEGORY 1/CATEGORY 2/..../CATEGORY n/BOOKNAME, 现在要重新格式化这些书的格式. 第nn个category前面需要有4(n-1)4(n1)个空格, 如果这本书在第nn个category上, 那么它前面要有4n4n个空格. 同一category里面, category和书名都按照字典序排序, 但是category要排在书前面. 第一个category需要按照字典序排列.

题解: 用一个trie存结果, 然后一遍dfs进行输出. 需要注意的是同一个节点内要把category和书名分开存.

【代码】

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAXN = 350;
const int LEN = 105;
char book[MAXN][LEN];
char* dir[MAXN];
int dirLen;
bool cmp(char *a, char *b)
{
	return strcmp(a, b) < 0;
}
struct Node{
	int left;
	int bro;
	char *str;
	bool book;
}node[MAXN];
int nodeLen = 0;
int head = 0;
int NewNode(char *str)
{
	if (!head)
	{
		head = nodeLen;
	}
	node[nodeLen].left = node[nodeLen].bro = 0;
	node[nodeLen].str = str;
	node[nodeLen].book = false;
	return nodeLen++;
}
void Insert(int fat, int p, char *str)
{
	bool end = false;
	int i;
	i = 0;
	while (str[i] && str[i] != '/')
	{
		i++;
	}
	if (str[i] == 0)
	{
		end = true;
	}
	str[i] = 0;
	if (!p)
	{
		int q = NewNode(str);
		node[fat].left = q;
		if (!end)
		{
			Insert(q, 0, str + i + 1);
		}
		else
		{
			node[q].book = true;
		}
		return;
	}
	int q;
	while (p && strcmp(node[p].str, str) != 0)
	{
		q = p;
		p = node[p].bro;
	}
	if (!p)
	{
		p = NewNode(str);
		node[q].bro = p;
	}
	if (!end)
	{
		Insert(p, node[p].left, str + i + 1);
	}
	else
	{
		node[p].book = true;
	}
}
void Output(int level, int p)
{
	int q = p;
	if (!p)
	{
		return;
	}
	while (p)
	{
		if (node[p].left == 0)
		{
			p = node[p].bro;
			continue;
		}
		for (int i = 0; i < level; i++)
		{
			printf("    ");
		}
		printf("%s\n", node[p].str);
		Output(level + 1, node[p].left);
		p = node[p].bro;
	}
	p = q;
	while (p)
	{
		if (!node[p].book)
		{
			p = node[p].bro;
			continue;
		}
		for (int i = 0; i < level; i++)
		{
			printf("    ");
		}
		printf("%s\n", node[p].str);
		p = node[p].bro;
	}
}
char str[LEN];
int main(void) {
#ifndef ONLINE_JUDGE
	//freopen("in.txt", "r", stdin);
//	freopen("out.txt", "w", stdout);
#endif
	int T;
	int ca = 0;
	while (gets(str))
	{
		ca++;
		dirLen = 0;
		strcpy(book[dirLen++], str);
		while (gets(str)&& strcmp(str, "0") != 0)
		{
			strcpy(book[dirLen++], str);
		}
		for (int i = 0; i < dirLen; i++)
		{
			dir[i] = book[i];
		}
		sort(dir, dir + dirLen, cmp);
		nodeLen = 1;
		head = 0;
		for (int i = 0; i < dirLen; i++)
		{
			if (!i || strcmp(dir[i], dir[i - 1]) != 0)
			{
				Insert(0, head, dir[i]);
			}
		}
		printf("Case %d:\n", ca);
		Output(0, 1);
	}
	return 0;
}


你可能感兴趣的:(ACM-ICPC国际大学生程序设计竞赛北京赛区(2016)网络赛 A)