SCU 4438 Censor(Hash)題解
阿新 • • 發佈:2018-11-02
題意:找出字串p中的w串刪除,反覆操作,直到找不到w,輸出這個串
思路:雜湊處理字首和,如果值相同就刪掉。
程式碼:
#include<iostream> #include<algorithm> #include<cstdio> #include<stdio.h> #include<string.h> #include<queue> #include<cmath> #include<map> #include<set> #include<vector> usingnamespace std; typedef unsigned long long ull; const int maxn = 5e6 + 10; const ull seed = 131; ull bin[maxn], Hash[maxn]; char p[maxn], w[maxn], ans[maxn]; void init(){ bin[0] = 1; for(int i = 1; i < maxn; i++) bin[i] = bin[i - 1] * seed; } int main(){ init(); while(~scanf("%s%s", w + 1, p + 1)){ int lenw = strlen(w + 1), len = strlen(p + 1); ull aim = 0; if(lenw > len){ printf("%s\n", p + 1); } else{ int point = 1; for(int i = 1; i <= lenw; i++) aim = aim * seed + w[i] - 'a'; Hash[0] = 0; for(int i = 1; i <= lenw - 1; i++){ Hash[point] = Hash[point - 1] * seed + p[i] - 'a'; ans[point++] = p[i]; } for(int i = lenw; i <= len; i++){ Hash[point] = Hash[point - 1] * seed + p[i] - 'a'; ans[point] = p[i]; if(point >= lenw && Hash[point] - Hash[point - lenw] * bin[lenw] == aim){ point -= lenw; } point++; } for(int i = 1; i < point; i++){ printf("%c", ans[i]); } printf("\n"); } } return 0; }