zoukankan      html  css  js  c++  java
  • 「CF126B」Password

    题目描述

    给定一个字符串 (S),我们规定一个字符串 (P) 是可行解,(P) 需要满足:

    1. (P)(S) 的前缀
    2. (P)(S) 的后缀
    3. (P) 出现在 (S) 中既不是前缀也不是后缀的地方

    题目要求出满足条件的长度最大的 (P),若存在输出该字符串,若不存在则输出Just a legend
    数据范围:(1leq |S|leq 10^6)


    解题思路

    我们可以发现一个切入点:
    对于我们找到的一个满足条件的字符串 (P),(假设它在 (S) 中的起始和终点坐标分别为 (l,r)
    那么我们发现(设 (|S|=n)):

    • (P) 既是 (S[1...r]) 的前缀,也是 (S[1...r]) 的后缀
    • (P) 既是 (S[l...n]) 的前缀,也是 (S[l...n]) 的后缀

    有没有想到什么?没错!( ext{KMP})
    而且我们还可以发现上述性质就是 (P) 满足条件的充要条件!
    所以我们只需要求出正反两个 (next) 数组,然后再枚举 (l) ,判断是否符合条件即可。
    总的复杂度是 (O(n)) 的。


    细节注意事项

    • 这题不要把 (S) 复制两次,我们可以用 reverse 函数将 (S) 反转(因为这题空间开得不大)
    • 注意字符串下标问题

    参考代码

    /*--------------------------------
    --Author: The Ace Bee-------------
    --Blog: www.cnblogs.com/zsbzsb----
    --This code is made by The Ace Bee
    --------------------------------*/
    #include <algorithm>
    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    #include <cstdio>
    #include <cctype>
    #include <cmath>
    #include <ctime>
    #define rg register
    #define clr(x, y) memset(x, y, sizeof x)
    using namespace std;
    
    const int _ = 1000010;
    
    char s[_]; int p[2][_];
    
    int main() {
    	scanf("%s", s + 1);
    	int n = strlen(s + 1);
    	p[0][1] = 0;
    	for (rg int j = 0, i = 1; i <= n; ++i) {
    		while (s[j + 1] != s[i + 1] && j) j = p[0][j];
    		if (s[j + 1] == s[i + 1]) ++j;
    		p[0][i + 1] = j;
    	}
    	reverse(s + 1, s + n + 1);
    	p[1][1] = 0;
    	for (rg int j = 0, i = 1; i <= n; ++i) {
    		while (s[j + 1] != s[i + 1] && j) j = p[1][j];
    		if (s[j + 1] == s[i + 1]) ++j;
    		p[1][i + 1] = j;
    	}
    	int pos = 0, mx = 0;
    	for (rg int i = 1; i <= n; ++i)
    		if (p[0][i] == p[1][n - i + p[0][i]])
    			if (mx < p[0][i]) mx = p[0][i], pos = i;
    	reverse(s + 1, s + n + 1);
    	if (pos == 0) puts("Just a legend");
    	else { for (rg int i = pos - mx + 1; i <= pos; ++i) putchar(s[i]); puts(""); }
    	return 0;
    }
    

    完结撒花 (qwq)

  • 相关阅读:
    Simulink模块之Zero-Order Hold和Unit Delay的区别
    芯片电源引脚的去耦电容
    STM32中电源引脚
    Simulink:模块参数初始化
    工作笔记1
    至少清楚知道兼容IE8 ie9 ;持续更新
    FROM_UNIXTIME/CONCAT
    采集文章
    文件上传类(引用)
    php文件相关操作
  • 原文地址:https://www.cnblogs.com/zsbzsb/p/11638191.html
Copyright © 2011-2022 走看看