nyoj 685 查找字符串

  當初一開始沒做出來。
後來,學習過一段時間之後,在返回來做這道題,忽然發現,map類容器可以做。
PS:需要注意的是:此題如果用c++的輸入輸出的話,會超時。
O(time):gets()<  scanf() < cin。  

附上代碼:

#include<stdio.h>
#include<map>
#include<string>
#include<string.h>
using namespace std;
map<string,int> mp;
char s[17];
int main()
{
    //freopen("a.txt","r",stdin);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,m;
        mp.clear();
        scanf("%d%d",&n,&m);
        getchar();
        while(n--)
        {
            gets(s);
            //puts(s);
            mp[s]++;
        }
        while(m--)
        {
            gets(s);
            printf("%d\n",mp[s]);
        }
    }
    return 0;
}


百度了一下,發現還可以用字典樹做。

現學了一下字典樹。

結構體:

typedef struct node
{
    struct node *next[MAX]; /*子節點個數 */
    int cnt;
}Trie;
ps:

<span style="white-space: pre;">	</span>Trie *root; /*定義根節點*/
一定要建立根節點並初始化。
關鍵核心就三個模塊:

1、建樹:

void creattree()
{
    int l=strlen(s);
    node *p=root,*q;
    for(int i=0; i<l; i++)  //對於每一位進行處理
    {
        int id=s[i]-'+';  //找到對應的位置
        if(p->next[id]==NULL)
        {
            q=new node;
            q->cnt=0;
            for(int j=0; j<mx; j++)
                q->next[j]=NULL;
            p->next[id]=q;
        }
        p->next[id]->cnt++;
        p=p->next[id];
    }
    p->cnt=-1;  //一段的結束標誌。
}

2、查找:

int find()
{
    int l=strlen(s);
    node *p=root;
    for(int i=0; i<l; i++)
    {
        int id=s[i]-'+';
        if(p->next[id]==NULL)
            return -1;          // 找不到相同串
        if(p->next[id]->cnt==-1)
        {
            if(i==l-1)
                return p->cnt;   //找到了相同串
            else
                return -1;   //找到了目標的子串
        }
        p=p->next[id];
    }
    return 0;   //目標爲某一串子串
}

3、大多的字典樹不要需釋放內存,但是如果內存不夠用,該應原還樹空間

<span style="color:#464646;">int deleteTrie(Trie *T)
{
    int i;
    if(T==NULL)return 0;
    for(i=0;i<MAX;i++)
    {
        if(T->next[i]!=NULL)
        deleteTrie(T->next[i]);
    }
    free(T);
    return 0;
}</span>

第三部分還沒用到,暫時還不清楚效果。




發佈了59 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章