Weighted String

#codeifyoucansolve
Given a string S which contains only lowercase characters [‘a’-‘z’] and an integer K you have to find number of substrings having weight equal to K.

Weight of characters is defined as :

Weight[‘a’]=1
Weight[‘b’]=2
Weight[‘c’]=3
Weight[‘d’]=4
Weight[‘e’]=5
Weight[‘f’]=6
Weight[‘g’]=7
Weight[‘h’]=8
Weight[‘i’]=9
Weight[‘j’]=10
Weight[‘k’]=11
Weight[‘l’]=12
Weight[‘m’]=13
Weight[‘n’]=14
Weight[‘o’]=15
Weight[‘p’]=16
Weight[‘q’]=17
Weight[‘r’]=18
Weight[‘s’]=19
Weight[‘t’]=20
Weight[‘u’]=21
Weight[‘v’]=22
Weight[‘w’]=23
Weight[‘x’]=24
Weight[‘y’]=25
Weight[‘z’]=26

Weight of a string will be defined as :

Weight[S[0]]+Weight[S[1]]+Weight[S[2]]……+Weight[S[Len-1]] where Len is length of string.

Similarly weight of substring string from index i and ending on position j will be defined as:

Weight[S[i]]+Weight[S[i+1]]+Weight[S[i+2]]……+Weight[S[j]]

Input:
First line of input contains number of test cases T and Each test case contains two lines first line contains value of integer K and second line contains the string S.

Output:
For each test case print the number of substrings having weight equal to K.

Constraints:
1<=T<=20
1<=K<=26*|S|
1<=|S|<=1000000
Sample Input (Plaintext Link)

2
5
abcdef
4
abcdef

Sample Output (Plaintext Link)

2
1

<?php

fscanf(STDIN,"%d\n",$T);
while($T--)
{
 fscanf(STDIN,"%d\n",$K);
  $str = trim(fgets(STDIN));
  $str = str_split($str);
  //print_r($str);
  $count = 0;
  foreach($str as $key => $value)
  {
   $num = ord($value) - 96;
     for($i=$key;$i<count($str)-1;$i++)
     {
      
      if($num > $K)
         break;
      if($num === $K)
      {
      $count +=1;
      break;
      }
      $num += (ord($str[$i+1]) - 96);
     }
  }
  print($count."\n");
 
}

?>

Run : http://ideone.com/boEj3L

ICPC Team Management.

#codeifyoucansolve
Little Chandan is an exceptional manager – apart from his role in HackerEarth – as the person who has to bug everyone, in general… and if possible, try to get some work done.

He’s also offered a job as the coach of the best Russian teams participating for ACM-ICPC World Finals. Now, Chandan is an extremely good coach, too. But he’s a weird person who thrives on patterns in life, in general. So, he has decided that if there are n number of students in total, and he is supposed to divide them in camps of k students – he want them to be arranged in such a way that the length of names of all the students in a camp is equal.

I know, totally weird, right?

Input:
The first line will contain the number of test cases. Which will be followed by two integers, n, k – denoting the number of total students, and the number of total students which will be allowed in one camp. After which, n lines will follow denoting the names of all the students who’re willing to learn by the great coach.

Output:
If it is possible for all the students be arranged in a camp of k students, print “Possible”, else print “Not possible”.

Constraints:
1 <= Test Cases <= 50
1 <= N <= 1000
1 <= K <= 1000
1 <= LengthOfAString <= 100
The name of a programmer will always be in lower case.

PS: n%k will ALWAYS be equal to zero – that is, it will possible to divide the n students in equal sized camps of k.
Sample Input (Plaintext Link)

2
6 3
arjit
tijra
genius
chanda
ashish
arjit
4 2
bond
coder
bond
lol

Sample Output (Plaintext Link)

Possible
Not possible

Explanation
In the first case, we can divide the six members into two teams of three with people having equal number of characters in their names. In the second case, we cannot do the same.

<?php
error_reporting(E_ERROR);
fscanf(STDIN,"%d\n",$T);
while($T--)
{
 $str = trim(fgets(STDIN));
 $str = explode(" ",$str);
 $N = intval($str[0]);
 $K = intval($str[1]);
 $rem = $N%$K;
 if($rem !== 0)
 {
 print("Not possible\n");
 continue;
 }
 $strarr = array();
 $div = $N/$K;
 while($N--)
 {
 $strarr[] = trim(fgets(STDIN));
 }
 $team = 0;
 $flag = 0;
 for($i=0;$i<count($strarr);)
 {
 $count = 1; 
 $index = $i+1;
 $team +=1;
 for($j=$i+1;$j<count($strarr);$j++)
 {
    if($count===$K)
    break;
 if(strlen($strarr[$i]) === strlen($strarr[$j]))
 {
 $temp = $strarr[$j];
 $strarr[$j] = $strarr[$index];
 $strarr[$index] = $temp;
 $index +=1;
 $count++;
 
 }
 }
 $i = $index;
 }
 if($div === $team && $flag !== 1)
    print("Possible\n");
 else
   print("Not possible\n");
 
}
?>

http://ideone.com/N3bntQ

Modify Sequence

#codeifyoucansolve
Suppose we have a sequence of non-negative integers, Namely a_1, a_2, … ,a_n. At each time we can choose one term a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros after several operations.

Input

The first line of test case is a number N. (0 < N <= 10000) The next line is N non-negative integers, 0 <= a_i <= 109

Output

If it can be modified into all zeros with several operations output “YES” in a single line, otherwise output “NO” instead.
Sample Input (Plaintext Link)

2
1 2

Sample Output (Plaintext Link)

NO

Explanation
It is clear that [1 2] can be reduced to [0 1] but no further to convert all integers to 0. Hence, the output is NO.

Consider another input for more clarification:

2
2 2

Output is YES as [2 2] can be reduced to [1 1] and then to [0 0] in just two steps.

<?php

fscanf(STDIN,"%d\n",$N);
$str = fgets(STDIN);
$str = trim($str);
$str = explode(" ",$str);
$min = 1;
for($i=0;$i<count($str)-1;$i++)
{
 if(intval($str[$i])<=intval($str[$i+1]))
 $min = intval($str[$i]);
    else
        $min = intval($str[$i+1]);
    $str[$i]=intval($str[$i]) - $min;
    $str[$i+1]=intval($str[$i+1]) - $min; 
}
$flag = 1;
foreach($str as $value)
{
 if(intval($value)  !== 0)
   $flag = 0;
}
if($flag)
 print("YES\n");
else
   print("NO\n");
?>

What is the string made of ?

#codeifyoucansolve
You are given a string, which contains entirely of decimal digits (0-9). Each digit is made of a certain number of dashes, as shown in the image below. For instance 1 is made of 2 dashes, 8 is made of 7 dashes and so on.

digits made of dashes

You have to write a function that takes this string message as an input and returns a corresponding value in terms of a number. This number is the count of dashes in the string message.

Note:

0 consists of 6 dashes, 1 consists of 2 dashes, 2 consists of 5 dashes, 3 consists of 5 dashes, 4 consists of 4 dashes, 5 consists of 5 dashes, 6 consists of 6 dashes, 7 consists of 3 dashes [though the figure shows that 7 consists of 4 dashes but due to minor mistake in the problem please write your solution assuming 7 consists of 3 dashes], 8 consists of 7 dashes, 9 consists of 6 dashes.

Constraints

String message will contain at least one digit, but not more than 100
Each character in code will be a digit (‘0’-‘9’).

Sample Input (Plaintext Link)

12134

Sample Output (Plaintext Link)

18

<?php
$val = fgets(STDIN);
$val = trim($val);
$val_arr = str_split($val);
//print_r($val_arr);
$sum = 0;
foreach($val_arr as $value)
{
 switch(trim($value))
    {
     case '0':
      $sum += 6;
      break;
    case '1' :
      $sum += 2;
      break;
    case '2' :
      $sum += 5;
      break;
    case '3' :
      $sum += 5;
      break;
    case '4' :
      $sum += 4;
      break;
    case  '5' :
       $sum += 5;
       break;
    case  '6' :
       $sum += 6;
       break;
    case  '7' :
       $sum += 3;
       break;
    case  '8' :
       $sum += 7;
       break;
    case  '9' :
       $sum += 6;
       break;
    }
}
print($sum."<br>")
?>

Fizz Buzz Test

#codeifyoucansolve
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Print a new line after each string or number.

<?php
for($val=1;$val<=100;$val++)
{
 if($val%15 === 0)
       print("FizzBuzz\n");
 else if($val%3 === 0)
     print("Fizz\n");
 else if($val%5 === 0)
     print("Buzz\n");
 else
    print($val."\n");
    
}

?>

Life, the Universe, and Everything

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely… rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Sample Input (Plaintext Link)

1
2
88
42
99

Sample Output (Plaintext Link)

1
2
88

<?php
while(fscanf(STDIN,"%d\n",$num))
{

        if($num == 42)
            break;
        echo $num."<br/>";
}

?>

Compile & Run : https://ideone.com/kkIhKV

PHP Implementation of 0-1 Knapsack Problem.

#codeifyoucansolve
PHP CLI Implementation of 0-1 Knapsack Problem.
T : testcase
N : number of next line input of price and weight
P : weight
Input Format
T
N P
Price Weight

Input
2
2 50
80 40
60 20
5 100
100 40
40 50
50 40
60 20
100 40
Output
80
260

<?php
fscanf(STDIN,"%d\n",$T);
while($T--)
{
 $str = trim(fgets(STDIN));
 $str = explode(" ",$str);
 $N = intval($str[0]);
 $P = intval($str[1]);
 $x = array();
 $y = array();
 while($N--)
 {
 $str = trim(fgets(STDIN));
 $str = explode(" ",$str);
 $x[] = intval($str[0]);
 $y[] =   intval($str[1]);
 }
 $k = array();
 for($i=0;$i<=count($x);$i++)
 {
 for($j=0;$j<=$P;$j++)
 {
 if($i===0 || $j ===0)
   $k[$i][$j]=0;
 else if($y[$i-1]<=$j)
  {
   $a = $x[$i-1]+$k[$i-1][$j-$y[$i-1]];
   $k[$i][$j]=($a>$k[$i-1][$j])?$a:$k[$i-1][$j];
  }
  else
    $k[$i][$j] = $k[$i-1][$j];
 }
 }
 print($k[count($x)][$P]."\n");
 
}

?>

http://ideone.com/Tfz3by

The Maximum Subarray

#codeifyoucansolve
Given an array A={a1,a2,…,aN} of N elements, find the maximum possible sum of a

Contiguous subarray
Non-contiguous (not necessarily contiguous) subarray.

Empty subarrays/subsequences should not be considered.
Input Format

First line of the input has an integer T. T cases follow.
Each test case begins with an integer N. In the next line, N integers follow representing the elements of array A.

Constraints:

1≤T≤10
1≤N≤105
−104≤ai≤104

The subarray and subsequences you consider should have at least one element.

Output Format

2 space separated integers denoting the maximum contiguous and non-contiguous subarray. At least one integer should be selected and put into the subarrays (this may be required in cases where all elements are negative).

Sample Input

2
4
1 2 3 4
6
2 -1 2 3 4 -5

Sample Output

10 10
10 11

Explanation

In the first case:
The max sum for both contiguous and non-contiguous elements is the sum of ALL the elements (as they are all positive).

In the second case:
[2 -1 2 3 4] –> This forms the contiguous sub-array with the maximum sum.
For the max sum of a not-necessarily-contiguous group of elements, simply add all the positive elements.

Copyright (c) 2015 HackerRank.
All Rights Reserved

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 100000
int main() {
    int T,flag;
    long int N;
    long int arr[MAX],i,max,max_1,max_2;
    scanf("%d",&T);
    while(T--)
        {
        scanf("%ld",&N);
        for(i=0;i<N;i++)
            scanf("%ld",&arr[i]);
        flag    =   max =   max_1 =  max_2   =   0;
        for(i=0;i<N;i++)
            {
            max     +=   arr[i];
            if(max<0)
                max  = 0;
            if(max_1<max)
                max_1 =   max;
            if(arr[i]>0)
                {
                max_2 += arr[i];
                flag    =   1;
            }
            
        }
        if(flag ==  0)
            printf("%ld %ld\n",arr[0],arr[0]);
        else
            printf("%ld %ld\n",max_1,max_2);
    }
    
    return 0;
}

********************************************************
Kadane’s Algorithm:

Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
return max_so_far

The Love-Letter Mystery

#codeifyoucansolve
James found a love letter his friend Harry has written for his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.

To do this, he follows 2 rules:

(a) He can reduce the value of a letter, e.g. he can change ‘d’ to ‘c’, but he cannot change ‘c’ to ‘d’.
(b) In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it until the letter becomes ‘a’. Once a letter has been changed to ‘a’, it can no longer be changed.

Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.

Input Format
The first line contains an integer T, i.e., the number of test cases.
The next T lines will contain a string each. The strings do not contain any spaces.

Output Format
A single line containing the number of minimum operations corresponding to each test case.

Constraints
1 ≤ T ≤ 10
1 ≤ length of string ≤ 104
All characters are lower case English letters.

Sample Input #00

4
abc
abcba
abcd
cba

Sample Output #00

2
0
4
2

Explanation

For the first test case, abc -> abb -> aba.
For the second test case, abcba is already palindromic string.
For the third test case, abcd -> abcc -> abcb -> abca = abca -> abba.
For the fourth test case, cba -> bba -> aba.

Copyright (c) 2015 HackerRank.
All Rights Reserved

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 10000
int main() {
    int T,i,j,sum;
    char str[MAX];
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        sum =   0;
        for(i=0,j=strlen(str)-1;i<j;i++,j--)
        {
            sum +=abs(str[i]-str[j]);
        }
        printf("%d\n",sum);
    }
    return 0;
}

Gcd Queries

#codeifyoucansolve
You are given an array A of integers of size N. You will be given Q queries where each query is represented by two integers L, R. You have to find the gcd(Greatest Common Divisor) of the array after excluding the part from range L to R inclusive (1 Based indexing). You are guaranteed that after excluding the part of the array
remaining array is non empty.
Input

First line of input contains an integer T denoting number of test cases.
For each test case, first line will contain two space separated integers N, Q.
Next line contains N space separated integers denoting array A.
For next Q lines, each line will contain a query denoted by two space separated integers L, R.

Output

For each query, print a single integer representing the answer of that query.
Constraints

Subtask #1: 40 points

2 ≤ T, N ≤ 100, 1 ≤ Q ≤ N, 1 ≤ A[i] ≤ 105
1 ≤ L, R ≤ N and L ≤ R

Subtask #2: 60 points

2 ≤ T, N ≤ 105, 1 ≤ Q ≤ N, 1 ≤ A[i] ≤ 105
1 ≤ L, R ≤ N and L ≤ R
Sum of N over all the test cases will be less than or equal to 106.

Example

Input:
1
3 3
2 6 9
1 1
2 2
2 3

Output:
3
1
2

Explanation

For first query, the remaining part of array will be (6, 9), so answer is 3.
For second query, the remaining part of array will be (2, 9), so answer is 1.
For third query, the remaining part of array will be (2), so answer is 2.

Warning : Large IO(input output), please use faster method for IO.

#include<stdio.h>
#define MAX 100000
unsigned long long gcd(unsigned long long x, unsigned long long y){
    unsigned long long wk;
    if(x<y){ wk=x;x=y;y=wk; }
    while(y){
        wk = x%y;
        x=y;
        y=wk;
    }
    return x;
}

unsigned long long gcd_a(unsigned long long N,unsigned long long n, unsigned long long a[MAX],long long l,long long r)
{
    unsigned long long num,i;
    if(n==1)
    {
     
     if((l-1)>=0)
       return a[0];
     else
       return a[r+1];
    }
    if(n==2)
    {
        if((l-1)>=0&&(r+1)<N)
        {
                return gcd(a[l-1], a[r+1]);
                
        }
        else if((l-1)<0&&(r+1)<N)
        {
                return gcd(a[r+1], a[r+2]);
        }
        else
          return gcd(a[0], a[1]);
    }
    else
    {
          if((r+1)>=N)
          {
                 num    =       gcd(a[0],a[1]);
                 for(i=2;i<l;i++)
                    num =       gcd(num,a[i]);
                 return num;
          }
          else if((l-1)>=0&&(r+1)<N)
          {
                if(l>1)
                {
                     num        =       gcd(a[0],a[1]);
                     for(i=2;i<l;i++)
                       num      =       gcd(num,a[i]);
                     for(i=r+1;i<N;i++)
                       num      =       gcd(num,a[i]);
                     return num;   
                }
                else
                {
                      num       =       gcd(a[0],a[r+1]);
                      for(i=r+2;i<N;i++)
                        num     =       gcd(num,a[i]);
                      return num;
                }
          }
          else
           {
                      num       =       gcd(a[r+1],a[r+2]);
                      for(i=r+3;i<N;i++)
                        num     =       gcd(num,a[i]);
                      return num;
           }
    }
}
inline unsigned long long get_input()
{
unsigned long long num=0,sign=1;
char d = getchar_unlocked();
if(d == '-')
 sign = -1;
while((d<'0'||d>'9') && d!=EOF&&d!='-')
 d = getchar_unlocked();
if(d == '-')
 sign = -1, d=getchar_unlocked();
while(d>='0' && d<='9')
{
 num=(num<<3)+(num<<1)+(d-'0');
 d=getchar_unlocked();
}
 return sign*num;
}
int main(void){
     unsigned long long T,N,Q,A[MAX],n,num,i; 
     long long L,R;
     T  =       get_input();
     while(T--)
     {
        N       =       get_input();
        Q       =       get_input();
        i       =       0;
        while(i<N)
        {
                A[i]    =       get_input();
                i++;
        }
        while(Q--)
        {
           L    =       get_input();
           R    =       get_input();
           n    =       N-(R-L+1);
           num  =       gcd_a(N,n, A,L-1,R-1);
           printf("%llu\n", num);
        }
     }    
    return 0;
}

http://www.codechef.com/viewplaintext/5726880

http://www.codechef.com/JAN15/status/GCDQ,vikasmcajnu