求公共前缀数目,最简单的字典树,耗内存,对比一下C++和G++下相同的代码运行结果:
G++虽然快点,但是直接MLE...所以交的时候还要注意选择编译器啊。可能是内存泄漏的原因。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define mst(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
struct trie{
struct trie *next[26];
int cnt;
bool exist;
};
trie* CreateNode(){
trie* node=new trie;
node->cnt=0;
node->exist=0;
memset(node->next,0,sizeof(node->next));
return node;
}
void InsertNode(trie *root,char *s){
trie *node=root;
char *p=s;
int pos=0;
while(*p){
pos = *p-'a';
if(node->next[pos]==NULL)
node->next[pos]=CreateNode();
node=node->next[pos];
p++;
node->cnt++;
}
node->exist = true;
}
//返回以所查字符串为前缀的次数
int SearchNode(trie *root,char *s){
trie *node=root;
char *p=s;
int pos=0;
while(*p){
pos=*p-'a';
node=node->next[pos];
p++;
if(node==NULL) return 0;
}
return node->cnt;
}
int main(){
trie *root=CreateNode();
char s[11];
bool flag=1;
while(gets(s)){
if(strlen(s)==0) {
flag=0;
continue;
}
if(flag)
InsertNode(root,s);
else printf("%d\n",SearchNode(root,s));
}
}
HDOJ1075 What are you talking about
给一组词及其对应翻译,然后每次给出一句话,输出这句话对应的翻译。是上一题的简单变形。
仍然用相同的代码来测一下C++和G++:
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cctype>
#include<cmath>
#include<algorithm>
#define mst(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
struct trie{
struct trie *next[26];
char tran[11];
bool exist;
};
trie* CreateNode(){
trie* node=new trie;
node->tran[0]=0;
node->exist=0;
memset(node->next,0,sizeof(node->next));
return node;
}
void InsertNode(trie *root,char *s,char *tr){
trie *node=root;
char *p=s;
int pos=0;
while(*p){
pos = *p-'a';
if(node->next[pos]==NULL)
node->next[pos]=CreateNode();
node=node->next[pos];
p++;
}
node->exist = true;
strcpy(node->tran,tr);
}
char* SearchNode(trie *root,char *s){
trie *node=root;
char *p=s;
int pos=0;
while(*p){
pos=*p-'a';
node=node->next[pos];
p++;
if(node==NULL) return 0;
}
if(node->exist)
return node->tran;
else return NULL;
}
int main(){
trie *root=CreateNode();
char s[3005],tran[11],tmp[15],*p;
scanf("%s",s);
while(scanf("%s",tran)&&strcmp(tran,"END")){
scanf("%s",s);
InsertNode(root,s,tran);
}
int pos=0;
scanf("%s",s);
getchar();
while(gets(s)&&strcmp(s,"END")){
for(int i=0;s[i];i++){
if(islower(s[i]))
tmp[pos++]=s[i];
else{
tmp[pos]='\0';
pos=0;
p=SearchNode(root,tmp);
if(p)
printf("%s",p);
else printf("%s",tmp);
printf("%c",s[i]);
}
}
printf("\n");
}
}