E - 最短的名字

xiaoxiao2021-02-27  158

在一个奇怪的村子中,很多人的名字都很长,比如aaaaa, bbb and abababab。 名字这么长,叫全名显然起来很不方便。所以村民之间一般只叫名字的前缀。比如叫'aaaaa'的时候可以只叫'aaa',因为没有第二个人名字的前三个字母是'aaa'。不过你不能叫'a',因为有两个人的名字都以'a'开头。村里的人都很聪明,他们总是用最短的称呼叫人。输入保证村里不会有一个人的名字是另外一个人名字的前缀(作为推论,任意两个人的名字都不会相同)。 如果村里的某个人要叫所有人的名字(包括他自己),他一共会说多少个字母? Input 输入第一行为数据组数T (T<=10)。每组数据第一行为一个整数n(1<=n<=1000),即村里的人数。以下n行每行为一个人的名字(仅有小写字母组成)。输入保证一个村里所有人名字的长度之和不超过1,000,000。 Output

对于每组数据,输出所有人名字的字母总数。

Sample Input 1 3 aaaaa bbb abababab Sample Output 5

一开始我用的是结构体来写,然后发现超时了,后来发现直接用string就可以实现

#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define N 1000000+10 #define INF 0x3f3f3f3f using namespace std; /*struct node {     char xx[N]; }Q[1010];*/ int main() {     int repeat;     int i,j;     scanf("%d",&repeat);     string xx[1010];     while(repeat--)     {         int n,sum=0;         scanf("%d",&n);         for(i=0;i<n;i++){             cin>>xx[i];         }         sort(xx,xx+n);         int temp = 1;         int flag = 1;         for(i=0;i<n-1;i++)         {           //  int count1=-INF;             for(j=0;j<xx[i].length()-1||j<xx[i+1].length()-1;j++)             {                 if(xx[i][j]!=xx[i+1][j])                     break;                 //if(i==j)                   //  continue;                 /*for(int k=0;k<strlen(Q[i].xx);k++)                 {                     if(Q[i].xx[k]==Q[j].xx[k])                         temp++;                     else{                         temp++;                         //printf("%d\n",temp);                         break;                     }                 }                 if(count1<=temp)                     count1 = temp;*/             }             temp=j+1;             if(flag<temp)                 sum += temp;             else                 sum += flag;             flag = temp;         }         sum+=temp;         printf("%d\n",sum);     }     return 0; }
转载请注明原文地址: https://www.6miu.com/read-16442.html

最新回复(0)