CodeForces 471D MUH and Cube Walls KMP

本文介绍了一个有趣的算法问题,即如何在一个由多个塔组成的熊墙中找到与大象墙相匹配的部分。通过将高度差转化为字符串并使用KMP算法进行匹配,可以高效地解决这一问题。

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

D. MUH and Cube Walls
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.

Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn’t give it a name. Their wall consists of n towers. Horace looked at the bears’ tower and wondered: in how many parts of the wall can he “see an elephant”? He can “see an elephant” on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace’s wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).

Your task is to count the number of segments where Horace can “see an elephant”.

Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears’ and the elephant’s walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears’ wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant’s wall.

Output
Print the number of segments in the bears’ wall where Horace can “see an elephant”.

Examples
input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
output
2
Note
The picture to the left shows Horace’s wall from the sample, the picture to the right shows the bears’ wall. The segments where Horace can “see an elephant” are in gray.


/*
KMP匹配 S[i]和P[i]分别代表文本串和模式串第i个位置的数字减去第i-1位置的数字 然后套KMP模版就行了
记得要特判N=1和W=1的情况 
W=1时直接输出N N=1而W!=1的时候输出0
*/

#include<stdio.h>
#include<string>
#include<cstring>
#include<queue>
#include<algorithm>
#include<functional>
#include<vector>
#include<iomanip>
#include<math.h>
#include<iostream>
#include<sstream>
#include<stack>
#include<set>
#include<bitset>
using namespace std;
const int MAX=200005;
int S[MAX],P[MAX],A[MAX];
int Next[MAX]= {0},N,W;
int main()
{
    cin.sync_with_stdio(false);
    cin>>N>>W;
    cin>>A[0];
    for (int i=1; i<N; i++)
    {
        cin>>A[i];
        S[i]=A[i]-A[i-1];
    }
    cin>>A[0];
    for (int i=1; i<W; i++)
    {
        cin>>A[i];
        P[i]=A[i]-A[i-1];
    }
    if (W==1)
    {
        cout<<N<<endl;
    }
    else if (N==1)
        cout<<0<<endl;
    else
    {
        memset(Next,0,sizeof(Next));
        Next[0]=-1;
        for (int i=1; i<W; i++)
        {
            int p=Next[i-1];
            while (p>=0&&P[p+1]!=P[i]) p=Next[p];
            Next[i]=p+1;
        }
        int ans=0;
        for (int i=1,p=0; i<N; i++)
        {
            while (p>=0&&P[p+1]!=S[i]) p=Next[p];
            if (++p==(W-1))
            {
                ans++;
                p=Next[p];
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
### 关于 Codeforces 平台上的 KMP 算法练习题目 对于希望在 Codeforces 上找到有关 KMP (Knuth-Morris-Pratt) 字符串匹配算法的练习题目的选手来说,可以关注几个特定标签下的问题。通常这些题目会被标记为 "strings" 或者更具体地标记为 "string suffix structures"[^1]。 为了帮助更好地理解如何查找适合的练习题目,在此提供一段 Python 代码用于模拟访问 API 获取带有指定标签的问题列表: ```python import requests def fetch_problems(tag, platform="codeforces"): url = f"https://{platform}.com/api/problemset.problems?tags={tag}" response = requests.get(url) if response.status_code != 200: raise Exception(f"Failed to retrieve data from {platform}") json_data = response.json() problem_list = [] for index, item in enumerate(json_data['result']['problems']): name = item["name"] rating = item.get('rating', 'N/A') contest_id = item["contestId"] index = item["index"] problem_info = { "Name": name, "Rating": rating, "Link": f"{platform}.com/contest/{contest_id}/problem/{index}" } problem_list.append(problem_info) return problem_list[:5] # Example usage with the tag related to string processing or specifically KMP pattern matching. kmp_related_tag = "strings" fetched_problems = fetch_problems(kmp_related_tag) for prob in fetched_problems: print(prob) ``` 这段脚本会调用 Codeforces 的公开 API 来获取前五个与字符串处理相关的编程挑战链接,并打印出来供参考。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值