POJ 3283 Card Hands Trie树

来源:互联网 发布:中国移动活动数据 编辑:程序博客网 时间:2024/06/06 00:48
  这题用的是字典树做,题意是给你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];}elsep = 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);elsea = 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);elsea = 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);elsea = 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);elsea = 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);elsea = 52, q.push(a);}}}add();}printf("%ld\n", ans);deal(root);}return 0;}

0 0
原创粉丝点击