• HDU2594 Simpsons’ Hidden Talents [KMP]


    Simpsons’ Hidden Talents

     Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 14056    Accepted Submission(s): 4839


    Problem Description
    Homer: Marge, I just figured out a way to discover some of the talents we weren’t aware we had.
    Marge: Yeah, what is it?
    Homer: Take me for example. I want to find out if I have a talent in politics, OK?
    Marge: OK.
    Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
    in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
    Marge: Why on earth choose the longest prefix that is a suffix???
    Homer: Well, our talents are deeply hidden within ourselves, Marge.
    Marge: So how close are you?
    Homer: 0!
    Marge: I’m not surprised.
    Homer: But you know, you must have some real math talent hidden deep in you.
    Marge: How come?
    Homer: Riemann and Marjorie gives 3!!!
    Marge: Who the heck is Riemann?
    Homer: Never mind.
    Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.
     
    Input
    Input consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.
     
    Output
    Output consists of a single line that contains the longest string that is a prefix of s1 and a suffix of s2, followed by the length of that prefix. If the longest such string is the empty string, then the output should be 0.
    The lengths of s1 and s2 will be at most 50000.
     
    Sample Input
    clinton homer riemann marjorie
     
    Sample Output
    0 rie 3
     
    Source
     

     把字符串b接到字符串a后面,然后利用next数组求最长的前缀等于后缀的情况。通过令len=next[len]使len达到小于等于min(|a|,|b|)。

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 string a,b;
     4 int n,m;
     5 int nxt[100005];
     6 void getnxt(){
     7     int k = nxt[0] = -1;
     8     int j = 0;
     9     while(j < m+n){
    10         while( k != -1 && a[k] != a[j]) k = nxt[k];
    11         nxt[++j] = ++k;
    12     }
    13 }
    14 
    15 int main(){
    16     while(cin >> a >> b){
    17         n = a.length(); m = b.length();
    18         a += b;
    19         getnxt();
    20         int len = n+m;
    21         while(len > n || len > m) len = nxt[len];
    22         for (int i = 0;i < len;++i) cout << a[i];
    23         if (len) cout << " ";
    24         cout << len << endl;
    25     }
    26 }
  • 相关阅读:
    C# MVC模式设置404&500
    jQuery实现滚动条滚动到子元素位置(方便定位)
    Oracle数据库的导出导入
    Oracle之clob字段不能union的问题
    div中内容垂直居中的方法小结
    C#实现Oracle数据库插入clob字段类型数据
    C_结构体_笔记
    Practice_17_01_ABC
    Practice_17_01_GID
    【转】 vim显示行号、语法高亮、自动缩进的设置
  • 原文地址:https://www.cnblogs.com/mizersy/p/9556992.html
Copyright © 2020-2023  润新知