POJ 3283 Card Hands Trie樹

  這題用的是字典樹做,題意是給你N個人的牌,每個人的牌從後往前是一條鏈,如果鏈的深度相同且值一樣則無需創建節點,直接進入下一個,問最後共有幾個節點。這題運用映射的思想,把每種類型不同的牌映射爲1 - 52,這樣就能寫字典樹了。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stack>
#define mem(a) memset(a, 0, sizeof(a))
using namespace std;

stack<int> q;
long ans = 0;
	
struct trie_tree
{
    struct trie_tree *next[53];	
};

struct trie_tree *root;

void add()
{
	int a, i;
	struct trie_tree *p;
	p = root;
	while(!q.empty())
	{
		a = q.top();
		q.pop();
		if(p->next[a] == NULL)
		{
			p->next[a] = (struct trie_tree*)malloc(sizeof(struct trie_tree));
			for(i = 1;i <= 52;i++)
			p->next[a]->next[i] = NULL;
			ans++;
			p = p->next[a];
		}
		else
		p = p->next[a];
	}
	return;
}

void deal(struct trie_tree *q)
{
	int i;
	if(q != NULL)
	{
		for(i = 1;i <= 52;i++)
		{
			deal(q->next[i]);
		}
		free(q);
	}
	return;
}

int main(int argc, char *argv[])
{
	int a, i, len;
	long people, num;
	char ch[5];
	while(scanf("%ld", &people)&&people)
	{
		ans = 0;
		root = (struct trie_tree*)malloc(sizeof(struct trie_tree));
		for(i = 1;i <= 52;i++)
		root->next[i] = NULL;
		while(people--)
		{
			scanf("%ld", &num);
			while(num--)
			{
				mem(ch);
				scanf("%s", ch);
				len = strlen(ch);
				if(len == 3)
				{
					if(ch[2] == 'C')
					a = 10, q.push(10);
					else if(ch[2] == 'D')
					a = 23, q.push(a);
					else if(ch[2] == 'H')
					a = 36, q.push(a);
					else
					a = 49, q.push(a);
				}
				else
				{
					if(ch[1] == 'C')
					{
						if(ch[0] == 'A')
						a = 1, q.push(a);
						else if(ch[0] >= '2'&&ch[0] <= '9')
						a = ch[0] - '0', q.push(a);
						else if(ch[0] == 'J')
						a = 11, q.push(a);
						else if(ch[0] == 'Q')
						a = 12, q.push(a);
						else
						a = 13, q.push(a);
					}
					else if(ch[1] == 'D')
					{
						if(ch[0] == 'A')
						a = 14, q.push(a);
						else if(ch[0] >= '2'&&ch[0] <= '9')
						a = ch[0] - '0' + 13, q.push(a);
						else if(ch[0] == 'J')
						a = 24, q.push(a);
						else if(ch[0] == 'Q')
						a = 25, q.push(a);
						else
						a = 26, q.push(a);
					}
					else if(ch[1] == 'H')
					{
						if(ch[0] == 'A')
						a = 27, q.push(a);
						else if(ch[0] >= '2'&&ch[0] <= '9')
						a = ch[0] - '0' + 26, q.push(a);
						else if(ch[0] == 'J')
						a = 37, q.push(a);
						else if(ch[0] == 'Q')
						a = 38, q.push(a);
						else
						a = 39, q.push(a);
					}
					else if(ch[1] == 'S')
					{
						if(ch[0] == 'A')
						a = 40, q.push(a);
						else if(ch[0] >= '2'&&ch[0] <= '9')
						a = ch[0] - '0' + 39, q.push(a);
						else if(ch[0] == 'J')
						a = 50, q.push(a);
						else if(ch[0] == 'Q')
						a = 51, q.push(a);
						else
						a = 52, q.push(a);
					}
				}
			}
			add();
		}
		printf("%ld\n", ans);
		deal(root);
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章