zoukankan      html  css  js  c++  java
  • POJ 2001 Shortest Prefixes(字典树)

    题目地址:POJ 2001

    考察的字典树,利用的是建树时将每个点仅仅要走过就累加。最后从根节点開始遍历,当遍历到仅仅有1次走过的时候,就说明这个地方是最短的独立前缀。然后记录下长度,输出就可以。

    代码例如以下:

    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    #include <queue>
    #include <map>
    #include<algorithm>
    
    using namespace std;
    char s[1100][30];
    struct node
    {
        int flag;
        node *next[30];
    };
    node *newnode()
    {
        int i;
        node *p;
        p=new node;
        for(i=0;i<26;i++)
        {
            p->next[i]=NULL;
        }
        p->flag=0;
        return p;
    }
    void insert1(node *root, char *s)
    {
        int i, len=strlen(s), x;
        node *p=root;
        for(i=0;i<len;i++)
        {
            x=s[i]-'a';
            if(p->next[x]==NULL)
                p->next[x]=newnode();
            p=p->next[x];
            p->flag++;
        }
    }
    int seach(node *root, char *s)
    {
        int i, len=strlen(s), x, pos=len;
        node *p=root;
        for(i=0;i<len-1;i++)
        {
            x=s[i]-'a';
            p=p->next[x];
            if(p->flag==1)
            {
                pos=i+1;
                break;
            }
        }
        return pos;
    }
    int main()
    {
        node *root;
        root =newnode();
        int cnt=0, i, j, k;
        while(scanf("%s",s[cnt])!=EOF)
        {
            insert1(root,s[cnt]);
            cnt++;
        }
        for(i=0;i<cnt;i++)
        {
            printf("%s ",s[i]);
            k=seach(root,s[i]);
            for(j=0;j<k;j++)
            {
                printf("%c",s[i][j]);
            }
            printf("
    ");
        }
        return 0;
    }


  • 相关阅读:
    Python httpServer服务器(初级)
    分布式服务管理zookeeper的java api
    基于netty的异步http请求
    for之Python vs C#
    表单验证
    contact表单错误解决记录
    表单
    Django后台管理界面
    正则表达式替换和不包含指定字符串
    Django模型-数据库操作
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4005670.html
Copyright © 2011-2022 走看看