最短的名字(湖南省第八屆大學生計算機程序設計競賽)

最短的名字
Time Limit:5000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Description

在一個奇怪的村子中,很多人的名字都很長,比如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 


用字典樹。後面還有一個參考答案代碼,很短。
AC代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
char s[1001][10001];
struct node
{
    int v;
    char now;
    node *next[26];
};

node root;

void biuld(char *str)   //創建字典樹
{
    int i,len;
    len = strlen(str);
    node *p = &root,*q;
    for(i = 0; i < len; i++)
    {
        int id = str[i]-'a';
        if(p->next[id]==NULL)
        {
            q=(node *)malloc(sizeof(root));
            q->v = 1;
            for(int j = 0; j < 26; j++)
            {
                q->next[j] = NULL;
            }
            p->next[id] = q;
            p=p->next[id];
        }
        else
        {
            p->next[id]->v++;
            p=p->next[id];
        }
    }
}
/*void Dfs(int k,)
{

}*/

int findTrie(char *str)
{
    int i;
    int len=strlen(str);
    node *p=&root;
    for(i=0;i<len;i++)
    {
        int id=str[i]-'a';
        p=p->next[id];
        if(p->v<=1)
        {
            return i+1;
        }
    }
    return i;
}

int main()
{
    int sum;
    int t,n,i;
    scanf("%d",&t);
    while(t--)
    {
        for(i = 0; i < 26; i++)  //重置根節點
        {
            root.next[i] = NULL;
        }
        sum = 0;
        scanf("%d",&n);
        for(i = 0; i < n; i++)
        {
            scanf("%s",&s[i]);
            biuld(s[i]);
        }
        for(i = 0; i < n; i++)
        {
            sum+=findTrie(s[i]);
        }
        printf("%d\n",sum);

    }

    return 0;
}

參考代碼:
// Yiming Li
#include<cstdio>
#include<cstring> 
#include<vector>
#include<string>
#include<algorithm>
#include<cassert>
using namespace std;

vector<string> a;
char s[1010000];
int d[2000];

int main()
{
  int i,j,l,t,n,ans;
  scanf("%d",&t);
  assert(t<=10);
  for (l=0;l<t;l++)
  {
    scanf("%d",&n);
    assert(1<=n&&n<=1000);
    a.clear();
    int tot = 0;
    for (i=0;i<n;i++)
    {
      scanf("%s",s);
      tot += strlen(s);
      a.push_back(s);
    }
    assert(tot <= 1000000);
    sort(a.begin(),a.end());
    memset(d,0,sizeof(d));
    for (i=0;i+1<n;i++)
    {
      for (j=0;j<a[i].length()&&j<a[i+1].length();j++)
        if (a[i][j]!=a[i+1][j]) break;
      if (j+1>d[i]) d[i]=j+1;
      if (j+1>d[i+1]) d[i+1]=j+1;
    }
    ans=0;
    for (i=0;i<n;i++)
      ans+=d[i];
    printf("%d\n",ans);
  }
  return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章