hdu 1800 Flying to the Mars(字典树统计)

此题很明显的一个谈心就是找重复的数最多的那个出现的次数就是答案,但是因为有前导0的存在,所以还得先处理下再插入到字典树中去。

其实如果数据小的话还可以用map进行hash。

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2016
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
using namespace std;
#define MEM(x,y) memset(x, y,sizeof x)
#define pk push_back
#define lson rt << 1
#define rson rt << 1 | 1
#define bug cout << "BUG HERE\n"
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
typedef pair<ii,int> iii;
const double eps = 1e-10;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int nCase = 0;
struct node {
	int cnt;
	node* nxt[10];
	node() {
		cnt = 0;
		for (int i = 0;i < 10;++i)
			nxt[i] = NULL;
	}
}*root;
char s[33];
int maxNumber;
void insert(int pos, char* s) {
	int len = strlen(s);
	node* p = root;
	for (;pos < len;pos++) {
		int id = s[pos] - '0';
		if (p->nxt[id] == NULL) p->nxt[id] = new node();
		p = p->nxt[id];
	}
	p->cnt++;
	if (p->cnt > maxNumber) maxNumber = p->cnt;
}
void del(node* p) {
	for (int i = 0;i < 10;++i)
		if (p->nxt[i] != NULL) del(p->nxt[i]);
	delete p;
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int n;
	while(~scanf("%d",&n)) {
		root = new node();
		maxNumber = 0;
		for (int i = 0;i < n;++i) {
			scanf("%s", s);
			int pos = 0;
			int len = strlen(s);
			while(pos < len && s[pos] == '0') pos++;
			if (pos != len) insert(pos, s);
			else {
				s[0] = '0';
				s[1] = 0;
				pos = 0;
				insert(pos, s);
			}
		}
		printf("%d\n", maxNumber);
		del(root);
	}
	return 0;
}


你可能感兴趣的:(字典树)