【题解】「BZOJ3916」friends(字符串Hash)

本文探讨了一种算法挑战,即从一个已知的修改后的字符串中逆向寻找原始字符串的方法。通过使用字符串Hash技术和枚举策略,文章详细解释了如何在复杂条件下识别并验证原始字符串的存在性和唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题面

【题目描述】
有三个好朋友喜欢在一起玩游戏,A君写下一个字符串S,B君将其复制一遍得到T,C君在T的任意位置(包括首尾)插入一个字符得到U.现在你得到了U,请你找出S.
【输入】
第一行一个数N,表示U的长度.
第二行一个字符串U,保证U由大写字母组成
【输出】
输出一行,若S不存在,输出"NOT POSSIBLE".若S不唯一,输出"NOT UNIQUE".否则输出S.
【样例输入】

7
ABCXABC

【样例输出】

ABC

【数据范围】
对于100%的数据 2<=N<=2000001

算法分析

字符串Hash
根据题意,直接模拟即可。
枚举插入的字符,判断剩下的字符串分成两部分后是否相同即可,枚举时需要判断不同情况,且需要注意子串是否唯一。判断相等时间复杂度O(1),总时间复杂度为O(N)。

参考程序

106
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define b 31
#define N 2000100 
using namespace std; 
unsigned int ha[N],p[N],n,ha1=0;
char s1[N];
bool check(int x,int y)     //判断找到的子串是否一致(如AAAAA,可以在任何地方插入,但子串唯一AA) 
{
    int t;
    if(ha1)		
    {
        t=ha[y]-ha[x-1]*p[y-x+1];
        if(t!=ha1) return 1;			//不唯一返回1
        else return 0;
    }
    else
    {
        ha1=ha[y]-ha[x-1]*p[y-x+1];		//记录找到的字符串的Hash值
        return 1;
    }
} 
int main()
{
    p[0]=1;
    for(int i=1;i<=N;i++)		//预处理b的次方
    p[i]=p[i-1]*b;
    scanf("%d %s",&n,s1); 
    ha[0]=s1[0]-'A'+1;
    for(int i=1;i<n;i++)			//字符串前缀hash
        ha[i]=ha[i-1]*b+(s1[i]-'A'+1);
//  for(int i=0;i<n;i++)
//      cout<<ha[i]<<" ";
//  cout<<endl;
    int ans=0,w;
    if(n%2==0) {printf("NOT POSSIBLE\n");return 0;}		//偶数无解
    if((ha[n/2]-ha[0]*p[n/2])==(ha[n-1]-ha[n/2]*p[n/2])) { if(check(1,n/2)) {ans++;w=0;} }  //在首位插入 
//  cout<<ha[n/2-1]<<" "<<ha[n-2]-ha[n/2-1]*p[n/2]<<" "; 
    if(ha[n/2-1]==(ha[n-2]-ha[n/2-1]*p[n/2])) {if(check(0,n/2-1)) {ans++;w=n-1;}}   //在尾插入
    if(ha[n/2-1]==(ha[n-1]-ha[n/2]*p[n/2]))  {if(check(0,n/2-1)) {ans++;w=n/2;}}    //在中间插入
    for(int k=1;k<n/2;k++)       //在左半部分插入 
    {
        unsigned int t1=ha[k-1]*p[n/2-k]+ha[n/2]-ha[k]*p[n/2-k];
        unsigned int t2=ha[n-1]-ha[n/2]*p[n/2];
    //  cout<<t1<<" "<<t2<<endl;
        if(t1==t2&&check(n/2+1,n-1)) 
        {
            ans++;w=k;
        } 
    }
    for(int k=n/2+1;k<n-1;k++)   //在右半部分插入 
    {
        unsigned int t1=ha[n/2-1];
        unsigned int t2=(ha[k-1]-ha[n/2-1]*p[k-n/2])*p[n-k-1]+(ha[n-1]-ha[k]*p[n-k-1]);
    //  cout<<t1<<" "<<t2<<endl;
        if(t1==t2&&check(0,n/2-1)) 
        {
            ans++;w=k;
        } 
    }
    if(ans==0) printf("NOT POSSIBLE\n");
    else if(ans>1) printf("NOT UNIQUE\n");
    else
    {
        if(w==0)
        {
            for(int i=1;i<=n/2;i++)
                printf("%c",s1[i]);
        }
        else if(w==n-1)
        {
            for(int i=0;i<n/2;i++)
                printf("%c",s1[i]);
        }
        else if(w==n/2)
        {
            for(int i=0;i<n/2;i++)
                printf("%c",s1[i]);
        }
        else if(w<n/2)
        {
            for(int i=0;i<=n/2;i++)
                if(i==w) continue;
                else printf("%c",s1[i]);    
        }
        else
        {
            for(int i=0;i<n/2;i++)
                printf("%c",s1[i]);
        }
    } 
 
    return 0; 
}  
### BZOJ1461 字符串匹配 题解 针对BZOJ1461字符串匹配问题,解决方法涉及到了KMP算法以及树状数组的应用。对于此类问题,朴素的算法无法满足时间效率的要求,因为其复杂度可能高达O(ML²),其中M代表模式串的数量,L为平均长度[^2]。 为了提高效率,在这个问题中采用了更先进的技术组合——即利用KMP算法来预处理模式串,并通过构建失配树(也称为失败指针),使得可以在主串上高效地滑动窗口并检测多个模式串的存在情况。具体来说: - **前缀函数与KMP准备阶段**:先对每一个给定的模式串执行一次KMP算法中的pre_kmp操作,得到各个模式串对应的next数组。 - **建立失配树结构**:基于所有模式串共同构成的一棵Trie树基础上进一步扩展成带有失配链接指向的AC自动机形式;当遇到某个节点不存在对应字符转移路径时,则沿用该处失配链路直至找到合适的目标或者回到根部重新开始尝试其他分支。 - **查询过程**:遍历整个待查文本序列的同时维护当前状态处于哪一层级下的哪个子结点之中,每当成功匹配到完整的单词就更新计数值至相应位置上的f_i变量里去记录下这一事实。 下是简化版Python代码片段用于说明上述逻辑框架: ```python from collections import defaultdict def build_ac_automaton(patterns): trie = {} fail = [None]*len(patterns) # 构建 Trie 树 for i,pattern in enumerate(patterns): node = trie for char in pattern: if char not in node: node[char]={} node=node[char] node['#']=i queue=[trie] while queue: current=queue.pop() for key,value in list(current.items()): if isinstance(value,int):continue if key=='#': continue parent=current[key] p=fail[current is trie and 0 or id(current)] while True: next_p=p and p.get(key,None) if next_p:break elif p==0: value['fail']=trie break else:p=fail[id(p)] if 'fail'not in value:value['fail']=next_p queue.append(parent) return trie,fail def solve(text, patterns): n=len(text) m=len(patterns) f=[defaultdict(int)for _in range(n)] ac_trie,_=build_ac_automaton(patterns) state=ac_trie for idx,char in enumerate(text+'$',start=-1): while True: trans=state.get(char,state.get('#',{}).get('fail')) if trans!=None: state=trans break elif '#'in state: state[state['#']['fail']] else: state=ac_trie cur_state=state while cur_state!={}and'#'in cur_state: matched_pattern_idx=cur_state['#'] f[idx][matched_pattern_idx]+=1 cur_state=cur_state['fail'] result=[] for i in range(len(f)-1): row=list(f[i].values()) if any(row): result.extend([sum((row[:j+1]))for j,x in enumerate(row[::-1])if x>0]) return sum(result) patterns=["ab","bc"] text="abc" print(solve(text,text)) #[^4] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值