Hdu4821 String

String

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3897    Accepted Submission(s): 1175


Problem Description
Given a string S and two integers L and M, we consider a substring of S as “recoverable” if and only if
  (i) It is of length M*L;
  (ii) It can be constructed by concatenating M “diversified” substrings of S, where each of these substrings has length L; two strings are considered as “diversified” if they don’t have the same character for every position.

Two substrings of S are considered as “different” if they are cut from different part of S. For example, string "aa" has 3 different substrings "aa", "a" and "a".

Your task is to calculate the number of different “recoverable” substrings of S.
 
Input
The input contains multiple test cases, proceeding to the End of File.

The first line of each test case has two space-separated integers M and L.

The second ine of each test case has a string S, which consists of only lowercase letters.

The length of S is not larger than 10^5, and 1 ≤ M * L ≤ the length of S.
Output
For each test case, output the answer in a single line.
 
Sample Input
3 3 abcabcbcaabc
 
Sample Output
2
 
Source
 
Recommend
liuyiding   |   We have carefully selected several similar problems for you:  6263 6262 6261 6260 6259
 
 
题意:从母串找出一个长度M*L为子串,且子串满足M段的子串皆不相同,求满足条件的子串个数
 
题解 : hash , 刚开始把0—>L-1 |  len-M*L-1 作为起点 ,然后往map里加m个(下标一直加L), 然后判断map的大小,如果大小为m,则找到符合条件的。
然后加一个,删最前的一个,在进行判断 
 
 
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#define hash_dict(i,L)  hs[i]-hs[i+L]*xp[L]
using namespace std;
typedef unsigned long long ull;
const int N=1e5+7;
ull base=31;
ull xp[N],hs[N];
void init()
{
    xp[0]=1;
    for(int i=1;i<N;i++)
        xp[i]=xp[i-1]*base;
}
void get_hash(char str[],int n)  // 获取字符串str的hash值
{
    hs[n]=0;
    for(int i=n-1;i>=0;i--)
        hs[i]=hs[i+1]*base+(str[i]-'a'+1);
}

int main()
{
    char str[N];
    int m,l;
    init();
    while(~scanf("%d%d",&m,&l))
    {
         scanf("%s",str);
        int len=strlen(str);
        get_hash(str,len);
        int ans=0;
        map<ull,int>my;
        for(int i=0;i<l&&i<len-m*l;i++)
        {
            my.clear();
            for(int j=i;j<i+m*l;j+=l)
                my[hash_dict(j,l)]++;
            if(my.size()==m)
                ans++;
            for(int j=m*l+i; j<=len-l; j+=l)
            {
                int head=j-m*l;
                my[hash_dict(head,l)]--;
                if(my[hash_dict(head,l)]==0)
                    my.erase(hash_dict(head,l));
                my[hash_dict(j,l)]++;
                if(my.size()==m)
                    ans++;
            }
        }
        printf("%d
",ans);
    }
    return 0;
}
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/lemon-jade/p/8519758.html