zoukankan      html  css  js  c++  java
  • poj3450 Corporate Identity KMP+枚举

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

    给数个字符串,若这些字符串中拥有相同的子串,求最大长度的子串,长度相等取ASCII码小的。

    这题也是可以用KMP算法来解,用一个字符串枚举去匹配其它的串,找到一个最长的就可以了。当然时间要用得长一些了。

    Source Code

    Problem: 3450   User: 541780774
    Memory: 920K   Time: 282MS
    Language: G++  

    Result: Accepted

    Source Code

    #include <stdio.h>
    #include <stdlib.h>
    #include<string.h>
    #include<iostream>
    using namespace std;
    int next[202],n,T,flag,minlen;
    struct {
           char str[202];
           int len;
           }r,s[4004],t,ans;
    void get_next()//求模式串的“next[]”值
    {
         long i=0,j=-1;
         next[0]=-1;
         while(i<=t.len)
         {
           if(j==-1||t.str[i]==t.str[j])
             next[++i]=++j;
           else j=next[j];
         }
    }
    int kmp()
    {
        int h,i,j,max,min=99999;
        for(h=0;h<T;h++)
          if(h!=flag)
          {
              i=0;j=0;max=0;
              while(i<s[h].len&&j<t.len)
             {
                if(j==-1||s[h].str[i]==t.str[j])
                {
                  i++;j++;
                  if(j>max)
                     max=j;
                }
                else
                {
                     if(j>max)//匹配串与某主串最长的匹配长度max;
                     max=j;
                     j=next[j];
                }
             }
             if(max<min) //该匹配串与所有的主串的匹配长度max中取最小min
                min=max;
          }
             return min;
    }
    main()
    {
       long i,a,max;
       while(scanf("%d",&T),T)
       {
          getchar();
          minlen=99999;
          max=0;
          flag=10000;
          for(i=0;i<T;i++)
          {
             gets(s[i].str);
             s[i].len=strlen(s[i].str);
             if(s[i].len<minlen)
             {
              minlen=s[i].len;
              flag=i; //标记长度最小的字符,做为子串;其它串做为主串
             }
          }
          for(i=0;i<minlen;i++)
          {
            strcpy(t.str,s[flag].str+i);//枚举子串所有拿去匹配的串
            t.len=strlen(t.str);
            get_next();
            a=kmp();
            if(a>max)
            {
               max=a;
               strncpy(ans.str,s[flag].str+i,a);
               ans.str[a]='\0';
            }
            else if(a==max)   //如果两字符串长度相等,取小串的;取ASCII码值小的串
            {
               strncpy(r.str,s[flag].str+i,a);
               r.str[a]='\0';
               if(strcmp(ans.str,r.str)>0)
                 strcpy(ans.str,r.str);
            }
          }
          if(max==0)
              printf("IDENTITY LOST\n");
          else
              printf("%s\n",ans.str);
       }
       system("pause");
    }

  • 相关阅读:
    详细解释ISupportInitialize接口
    微软发布了VS2005 IDE增强工具
    Oracle中无法解析TNS的陷阱
    Oracle临时表空间为何暴涨?
    欧洲游回来
    树比较的一个另类方法
    控件的Archor属性没有作用,是.Net的BUG?
    Oracle中取字段唯一值的一个sql语句的写法
    Qt程序的翻译
    Qt程序运行到Symbian手机上
  • 原文地址:https://www.cnblogs.com/zxj015/p/2740277.html
Copyright © 2011-2022 走看看