zoukankan      html  css  js  c++  java
  • poj 1251 统计难题(字典树)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

    AC代码:

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstdio>
     4 #include<cstring>
     5 #include<queue>
     6 #include<string>
     7 #include<cmath>
     8 using namespace std;
     9 char ss[1010][1010];
    10 #define MAX 27
    11 struct  trie
    12 {
    13     trie *next[MAX];
    14     int  v;
    15     trie()
    16     {
    17         int i;
    18         v=0;
    19         for(i=0; i<26; i++) next[i]=NULL;
    20     }
    21 };
    22 trie *p,*q;
    23 void creattrie(char *str,trie *root)
    24 {
    25     int len = strlen(str);
    26     p = root;
    27     for(int i=0;i<len; i++)
    28     {
    29         int id = str[i] - 'a';
    30         if(p->next[id] == NULL)
    31         {
    32             q=new trie;
    33             q->v = 1;
    34             p->next[id] = q;
    35             p=q;
    36         }
    37         else
    38         {
    39             p=p->next[id];
    40             p->v+=1;
    41         }
    42     }
    43 }
    44 int findtrie(char *str,trie *root)
    45 {
    46     int i;
    47     int len = strlen(str);
    48     p = root;
    49     for(i=0;i<len;i++)
    50     {
    51         int id = str[i] - 'a';
    52         p=p->next[id];
    53         if(p->v == 1)
    54         {
    55             return i+1;
    56         }
    57     }
    58 }
    59 int main()
    60 {
    61 int T,n,ans;
    62 scanf("%d",&T);
    63 while(T--)
    64 {
    65     ans = 0;
    66     trie *root = new trie;
    67     scanf("%d",&n);
    68     //getchar();
    69     for(int i=0;i<n;i++)
    70     {
    71         scanf("%s", ss[i]);//用gets接收错了一天了,晚上才发现
    72         creattrie(ss[i],root);
    73     }
    74     for(int i=0;i<n;i++)
    75     {
    76         int kk = findtrie(ss[i],root);
    77         ans = ans+kk;
    78     }
    79     printf("%d
    ",ans);
    80 }
    81   return 0;
    82 }
  • 相关阅读:
    示例 json with js
    JS json
    jquery
    发布包规范
    20180320待编辑
    CefSharp中c#和js交互
    列举mvc ActionResult的返回值
    怎么实现第三方登录
    mvc @Html控件
    MVC webuploader 图片
  • 原文地址:https://www.cnblogs.com/lovychen/p/4475891.html
Copyright © 2011-2022 走看看