题目大意:方师傅过生日啦,于是蟹毛买了N个
01
串,想送给方师傅,但是蟹毛觉得这些
01
串不够美,于是他想从中选出一些送给方师傅,蟹毛对于p个
01
串的美值定义为: 这些
01
串的最长公共前缀的长度×p,所以蟹毛想从N个
01
串中选出一些,使得这些
01
串的美值最高,请告诉蟹毛最好的美值是多少。
代码实现:
#include<iostream>
#include<string>
#include<cstdlib>
#define Max(a,b) ((a)>(b)?(a):(b))
using namespace std;
int max_v;
struct tree{
int cnt;
tree *next[2];
}*root;
tree *Create(){
tree *p;
p=(tree *)malloc(sizeof(tree));
p->cnt=0;
for(int i=0;i<2;++i) p->next[i]=NULL;
return p;
}
void Insert(string &str){
tree *p=root;
int i=0,x;
while(str[i]){
x=str[i++]-'0';
if(p->next[x]==NULL) p->next[x]=Create();
p=p->next[x];
p->cnt++;
}
}
void Search(tree *p,int le){
max_v=Max(max_v,p->cnt*le);
if(p->next[0]!=NULL) Search(p->next[0],le+1);
if(p->next[1]!=NULL) Search(p->next[1],le+1);
}
int main(){
int n;
string str;
while(cin>>n){
root=Create();
while(n--){
cin>>str;
Insert(str);
}
max_v=0;
Search(root,0);
cout<<max_v<<endl;
}
}
结构体tree里维护两个变量:从cnt 和 deep,结果即为 cnt*deep 的最大值
#include<iostream>
#include<string>
#include<cstdlib>
#define Max(a,b) ((a)>(b)?(a):(b))
using namespace std;
int max_v;
struct tree{
int cnt,deep;
tree *next[2];
}*root;
tree *Create(){
tree *p;
p=(tree *)malloc(sizeof(tree));
p->cnt=0,p->deep=0;
for(int i=0;i<2;++i) p->next[i]=NULL;
return p;
}
void Insert(string &str){
tree *p=root;
int i=0,x;
while(str[i]){
x=str[i++]-'0';
if(p->next[x]==NULL) p->next[x]=Create();
p->next[x]->deep=p->deep+1;
p=p->next[x];
p->cnt++;
max_v=Max(max_v,p->cnt*p->deep);
}
}
int main(){
int n;
string str;
while(cin>>n){
root=Create();
max_v=0;
while(n--){
cin>>str;
Insert(str);
}
cout<<max_v<<endl;
}
}