Cod sursa(job #1052591)

Utilizator cdascaluDascalu Cristian cdascalu Data 11 decembrie 2013 16:41:14
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.36 kb
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#include <unordered_map>
#define B 123
#define Nmax 17000
using namespace std;

char buf[Nmax];
int N,K,sol = 1, sol_max =-1;
int run(int sz)
{
    unordered_map<unsigned int, int> hash;
    string x = "";
    unsigned key = 0,power = 1;
    for(int i=0;i<sz;++i)
    {
        if(i!=0)
            power *= B;

        key = (key*B + buf[i]);
    }
    hash[key] = 1;
    int maxim=1;

    for(int i=sz;i<N;++i)
    {
        key = (key - power * buf[i-sz])*B + buf[i];

        if(hash.find(key) != hash.end())
            hash[key] = hash[key] + 1;
        else
            hash[key] = 1;
        if(hash[key] > maxim)
            maxim = hash[key];
    }
    return maxim;
}
int main()
{
    ifstream f("substr.in");
    f>>N>>K;
    f.getline(buf,Nmax);
    f.getline(buf,Nmax);

    f.close();


    int left,right,mid;
    left = 1;right = N;

    while(left<=right)
    {
        mid = (left+right)/2;
        int x = run(mid);

        if(x >= K)
        {
            if(mid > sol)
                sol = mid;
            left = mid+1;
        }
        else
        {
            right = mid-1;
        }
    }
    ofstream g("substr.out");
    g<<sol<<"\n";
    g.close();
    return 0;
}