Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE
Showing posts with label Z-function. Show all posts
Showing posts with label Z-function. Show all posts

Wednesday, November 5, 2014

SUFEQPRE-Suffix Equal Prefix

Suffix Equal Prefix

Given below code is for SUFEQPRE spoj or suffix equal prefix spoj.

Hint :-> Read Z-function . After that this question is just simple implementation of  Z-function.


#include <bits/stdc++.h>
using namespace std;
int Z_function(char s[] , int n)
{
    int z[n+9] , count = 0;
    memset(z , 0 , sizeof z);
    int l=0,r=0;
    z[0] = n;
    for(int i=1;i<n;i++)
    {
        if(i<=r)
            z[i] = min(r-i+1 , z[i-l]);
        while(i+z[i] < n && s[z[i]] == s[i+z[i]])
            z[i]++;
        if(i+z[i]-1 > r)
            l = i, r = i+ z[i] - 1;
        if(z[i] == n - i)
            count ++;
    }
    return count;
}
int main()
{
    int t , n , j = 1;
    char s[1000009];
    scanf("%d ",&t);
    while(t--)
    {
        gets(s);
        n = strlen(s);
        printf("Case %d: %d\n",j,Z_function(s , n));
        j++;
    }
    return 0;
}

Sunday, October 5, 2014

FILRTEST-File Recover Testing

File Recover Testing

Below given code is for filrtest spoj or file recover testing spoj.

Hint:-  For solving this question you should Know z-function . If you know z-function of a string then its very to calculate the number of string in given length.


#include <bits/stdc++.h>
using namespace std;
int *Z_function(char s[])
{
    int *z;
    z = (int*)calloc((strlen(s)+9),sizeof(int));
    int l=0,r=0,n = strlen(s);
    z[0] = n;
    for(int i=1;i<n;i++)
    {
        if(i<=r)
            z[i] = min(r-i+1 , z[i-l]);
        while(i+z[i] < n && s[z[i]] == s[i+z[i]])
            z[i]++;
        if(i+z[i]-1 > r)
            l = i, r = i+ z[i] - 1;
    }
    return z;
}
int main()
{
    int n;
    while(1)
    {
        char s[1000009];
        scanf("%d",&n);
        scanf("%s",s);
        if(n==-1)
            return 0;
        int *z;
        int size = strlen(s);
        if(n<size)
        {
            printf("0\n");
            continue;
        }
        z = (int*)calloc((size+9),sizeof(int));
        z = Z_function(s);
        int m = 0;
        for(int i=1;i<size;i++)
        {
            if(i+z[i] == size)
                m = max(m , z[i]);
        }
        int total;
        total = (n-m)/(size - m);
        printf("%d\n",total);
    }
    return 0;
}