Wednesday 27 May 2015

light oj-1255

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char pat[1000009];
char txt[1000009];

int count;
void f_f(char *pat, int *f)
{
    f[0]=0;

    int len = 0,k=1;
   int p=strlen(pat);

     while (k < p)
     {
       if (pat[k] == pat[len])
        {
           len++;
           f[k]=len;
           k++;
        }
       else
       {
         if (len!=0) len = f[len-1];

         else
         {
             f[k]=0;
             k++;
         }
       }
    }
}

int KMPSearch(char *pat, char *txt)
{
    int p = strlen(pat);
    int t = strlen(txt);
int *f = (int *)malloc(sizeof(int)*p);

f_f(pat,f);

    int i  = 0,j=0;

     while (i < t)
    {
      if (pat[j] == txt[i])
      {
        j++;
        i++;
      }

      if (j == p)
      {
          count++;
           j = f[j-1];
         }

      else if (pat[j] != txt[i])
     {
        if (j!=0)
            j= f[j-1];

        else
            i++;

        }
}
free(f);

}
int main()
{
    int test,z=0,c;


    scanf("%d",&test);
     for(z=1;z<=test;z++){


      scanf("%s %s",txt,pat);
      count=0;
      KMPSearch(pat, txt);

    printf("Case %d: %d\n",z,count);}

    }

light oj 1007....Mathematically Hard

 #include<stdio.h>
 #define max 5000009

 unsigned long long phi[max];
int main()
 {
  unsigned   long long i,j;
   for(i=2;i<max;i++){
    if(phi[i]==0){
        phi[i]=i-1;

        for(j=i*2;j<max;j=j+i){
                if(phi[j]==0){

            phi[j]=j;
                }
            phi[j]=phi[j]-(phi[j]/i);
        }
      }
    }
   unsigned   long long s,d=0;
     for(s=2;s<max;s++){
       phi[s]= phi[s]*phi[s];
         phi[s]=phi[s]+phi[s-1];
      }
     unsigned long long a,b,x,test,u;
      scanf("%llu",&test);
       for(u=1;u<=test;u++){
        scanf("%llu %llu",&a,&b);
          printf("Case %llu: %llu\n",u,phi[b]-phi[a-1]);
      }
   }