zoukankan      html  css  js  c++  java
  • poj 2001

    http://poj.org/problem?id=2001

    大意: 求一字符串的最短前缀

    解题思路:trie树的简单应用。。直接模版即可

     1 #include <iostream>
     2 #include<cstring>
     3 using namespace std;
     4 struct node{
     5     int cnt;
     6     struct node *next[26];
     7     node(){//结构体中可以带函数,进行初始化
     8         cnt =0;
     9         memset(next,0,sizeof(next));
    10     }
    11 };
    12 char str[1003][30];
    13 node *root = NULL;//初始化,,根节点不用。。
    14 
    15 void maketrie(char *s){
    16     node *p = root;
    17     node *temp = NULL;
    18     for(int i=0;i<strlen(s);i++){
    19         if(p->next[s[i]-'a']==NULL){//查看节点中是否有此节点。。没有的话加上,有的话。。cnt++;
    20             temp = new node;
    21             p->next[s[i]-'a']=temp;
    22         }
    23         p = p->next[s[i]-'a'];
    24         p->cnt++;
    25     }
    26 }
    27 
    28 void search(char *s){//输出。。如果其cnt==1 证明他是该字符串的最短前缀,没有于别的字符串公用该节点。
    29     node *p =root;
    30     for(int i=0;i<strlen(s);i++){
    31         p = p->next[s[i]-'a'];
    32         cout<<s[i];
    33         if(p->cnt==1)
    34             break;
    35     }
    36 }
    37 
    38 int main()
    39 {
    40     int num = 0;
    41     root = new node;
    42     while(cin>>str[num]){
    43         maketrie(str[num]);
    44         num++;
    45     }
    46 
    47     for(int i=0;i<num;i++){
    48         cout<<str[i]<<" ";
    49         search(str[i]);
    50         cout<<endl;
    51     }
    52     return 0;
    53 }
  • 相关阅读:
    浅谈c#中使用lock的是与非
    C#设计模式学习笔记单例模式
    ArrayList c.toArray might (incorrectly) not return Object[] (see 6260652)
    java.lang.Object 之 clone() 使用

    把以前的补齐 张
    String的方法 张
    随便写写 张
    集合框架 张
    java 张
  • 原文地址:https://www.cnblogs.com/Bang-cansee/p/3240192.html
Copyright © 2011-2022 走看看