hdu1251(统计难题)

学了字典树
来个模板题

比较习惯用数组

#include<bits/stdc++.h> ///用字典树求前缀 
#include<iostream> 
#include<ctype.h>
#include<map>
#include<set>
#include<iomanip>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 1e7+7;
const double eps = 1e-7;
const double pi=3.1415926;
const ll mod = 1e9+7;

int tre[1000010][26];		//分别为可能字符数与字母 
int num[1000010]={0};
int pos=1;
void insert(char str[]){			///建树 
	int cep=0;
	for(int i=0;str[i];i++){	
		int n=str[i]-'a';
		if(tre[cep][n]==0){
			tre[cep][n]=pos++;		///建立节点 
		}
		cep=tre[cep][n];		///建立叶节点
		num[cep]++;				///计数 
	}
}
int find(char str[]){			///查找
	int p=0;
	for(int i=0;str[i];i++){
		int n=str[i]-'a';
		if(tre[p][n]==0){		///没有ci前缀 
			return 0;
		}
		p=tre[p][n];		 
	}
	return num[p];
}
int main(){
	int a,b,c;
	char str[27]; 
	while(gets(str)){
		if(!strlen(str)){
			break;
		}
		insert(str);
	} 
	while(gets(str)){
		cout<<find(str)<<endl;
	}
	return 0;
}

也可以用map
不过会慢一些
偷懒

#include<iostream>			///map版本 
#include<map>
#include<string.h>
using namespace std;
typedef long long ll;
char ar[102],br[102];
int main(){
	int a,b,c;
    char str[15];
    map<string,int>ma;
    while(gets(str)){
    	int len=strlen(str);
    	if(len==0){
    		break;
		}
    	for(int i=len;i;i--){
    		str[i]='\0';
    		ma[str]++;
		}
	}
	while(gets(str)){
		cout<<ma[str]<<endl;
	}
    return 0;
}

(参考《算法竞赛-入门到进阶》-罗勇军 郭卫斌著)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值