Cod sursa(job #1047408)

Utilizator ELHoriaHoria Cretescu ELHoria Data 4 decembrie 2013 13:10:45
Problema Substr Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.15 kb
#include <fstream>
#include <unordered_map>

using namespace std;

ifstream cin("substr.in");
ofstream cout("substr.out");

const int mod = int(1e9) + 7;
int N, K;
string str;
int h[16385];
unordered_map<int,int> H;

inline int getIndex(char x) {
   return x - 'a' + 1;
}

void compute() {
    int X = 26;
    h[1] = getIndex(str[0]);
    for (int i = 2;i <= N;i++,X = 1LL * X * 26 % mod) {
        h[i] = 1LL * h[i - 1] * getIndex(str[i + 1]) * X % mod;
    }
}

int logpow(int a,int b) {
    int ret = 1;   
    for (;b > 0;b >>= 1, a = 1LL * a * a % mod) {
        if (b & 1) {
            ret = 1LL * ret * a % mod;
        }
    } 
    return ret;
}

bool isGood(int L) {
    int X = 1, hash;
    H.clear();
    for (int i = L; i <= N;i++,X = 1LL * X * 26 % mod) {
        hash = (h[i] - h[i - L]) * logpow(X,mod - 2);
        if(++H[hash] == K) {
             return true;
	}
    }
    return false;
}

int main()
{
    cin >> N >> K;
    cin.get();
    getline(cin,str);
    compute();
    int ans = 0;
    for (int step = 1 << 15;step > 0;step >>= 1) {
        if(step + ans <= N && isGood(step + ans)) {
	     ans += step;	
	}
    }
    cout << ans;
    return 0;  
}