HDU 2087 剪花布条(哈希写法)

来源:互联网 发布:服务器软件有哪些 编辑:程序博客网 时间:2024/06/08 11:04


剪花布条

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16919    Accepted Submission(s): 10694


Problem Description
一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
 

Input
输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。
 

Output
输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。
 

Sample Input
abcde a3aaaaaa aa#
 

Sample Output
03
 
写法1:边遍历边查询;

#include <iostream>#include <cstdio>#include <cstring>using namespace std;typedef unsigned long long ull;const int byte = 100000007;char a[1001], b[1001];ull haxi(int alen, int blen){    if(alen < blen) return 0;    ull t = 1, ahash = 0, bhash = 0, cnt = 0;    for(int i = 0; i < blen; i++) t *= byte;    for(int i = 0; i < blen; i++) ahash = ahash*byte + a[i];    for(int i = 0; i < blen; i++) bhash = bhash*byte + b[i];    for(int i = 0; i + blen <= alen; i++)    {        if(ahash == bhash)        {            cnt++;            ahash = ahash - a[i+blen-1] + '@';            a[i+blen-1] = '@';        }        if(i + blen < alen)            ahash = ahash*byte - a[i]*t + a[i+blen];    }    return cnt;}int main(){    while(cin >> a)        {            if(!strcmp(a, "#")) break;            cin >> b;            int alen = strlen(a);            int blen = strlen(b);            ull res = haxi(alen, blen);            cout << res << endl;        }    return 0;}
写法2:先都预处理 然后在根据条件用hash

#include<bits/stdc++.h>using namespace std;typedef unsigned long long ull;const int base = 233;const int maxn = 1e3+5;ull h[maxn], po[maxn];ull HASH(char *str, int len){    ull hsh = 0;    for(int i = 0; i < len; i++)        hsh = hsh*base+str[i];    return hsh;}void init_hsh(char *str, int len){    for(int i = 0; i < len; i++)        h[i+1] = h[i]*base+str[i];}void init_po(void){    ull res = 1;    for(int i = 1; i < maxn; i++)    {        res *= base;        po[i] = res;    }}int main(void){    init_po();    char str[maxn], tstr[maxn];    while(scanf(" %s", str), str[0] != '#')    {        scanf(" %s", tstr);        int len1 = strlen(str);        int len2 = strlen(tstr);        init_hsh(str, len1);        ull mt = HASH(tstr, len2);        ull ans = 0;        for(int i = 1; i+len2-1 <= len1; i++)            if(h[i+len2-1]-h[i-1]*po[len2] == mt)                ans++, i += len2-1;        cout << ans << endl;    }    return 0;}


1 0
原创粉丝点击