Ice Cream Parlor

Sunny and Johnny together have M dollars and want to spend the amount at an ice cream parlour. The parlour offers N flavors, and they want to choose 2 flavors so that they end up spending the whole amount.

You are given a list of cost of these N flavors. The cost of ith flavor is denoted by (ci). You have to display the indices of two flavors whose sum is M.

Input Format

The first line of the input contains T, T test cases follow.
Each test case follows the format: The first line contains M. The second line contains N. The third line contains N single space separated integers denoting the price of each flavor. Here, ith integer denotes ci.

Output Format

Output two integers, each of which is a valid index of the flavor. The lower index must be printed first. Indices are indexed from 1 to N.

Constraints

1 ≤ T ≤ 50
2 ≤ M ≤ 10000
2 ≤ N ≤ 10000
1 ≤ ci ≤ 10000
The prices of two items may be same and each test case has a unique solution.

Sample Input

2
4
5
1 4 5 3 2
4
4
2 2 4 3

Sample Output

1 4
1 2

Explanation

The sample input has two test cases. For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sums to 4. For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sums to 4.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits
7433 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 10000
int main() {
    int T,N,M,c[MAX],i,j,max,i1,i2;
    scanf("%d",&T);
    while(T--)
        {
        max=0;
        i1=1;
        i2=2;
        scanf("%d%d",&M,&N);
        for(i=0;i<N;i++)
            scanf("%d",&c[i]);
        for(i=0;i<(N-1);i++)
            {
            for(j=i+1;j<N;j++)
                {
                if((c[i]+c[j])>max && (c[i]+c[j])<= M)
                    {
                    max=c[i]+c[j];
                    i1=i+1;
                    i2=j+1;
                    if((c[i]+c[j]) == M)
                        break;
                }
                if((c[i]+c[j])==M)
                    break;
                    
            }
        if((c[i]+c[j])==M)
             break;           
        }
       printf("%d %d\n",i1,i2); 
    }
    return 0;
}

Compile & Run : http://ideone.com/TGi0zG
Follow On Twitter : https://twitter.com/codeifucansolve
Quora Blog : http://codeifyoucansolve.quora.com/Ice-Cream-Parlor

Manasa loves Maths

You are given an integer N. Is there a permutation of digits of integer that’s divisible by 8? A permutation of digits of integer N is defined as an integer formed by rearranging the digits of N. For example, if the number N = 123, then {123, 132, 213, 231, 312, 321} are the possible permutations.

Input Format
The first line contains an integer T i.e. number of test cases.
T lines follow, each containing the integer N.

Output Format
For each test case print YES if there exists one such re-arrangement of N such that it is divisible by 8 or NO if there isn’t.

Constraints
1 <= T <= 45
0 <= N <= 10110

Note
Re-arrangements of 10 are {10, 01} which boils down to {10, 1}.

Sample Input

2
61
75

Sample Output

YES
NO

Explanation
Test case #00: 16 is permutation of 61 which is divisible by 8.
Test case #01: None of permutation of 75, {57, 75}, are divisible by 8.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits

Choose a translation

300 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int val[10];
int flag = 0;
void permute(int i,int n)
    {
    int j,k,t;
    long int N;
    if(i == n)
    {
       N=0;
       for(k=0;k<=n;k++)
           N = N*10 + val[k];
       N = N % 1000;
       if(flag == 0)
           {
           if(N%8 == 0)
               flag =1;
       }
       //printf("%ld\n",N);
    }
    else
        {
        for(j=i;j<=n;j++)
        {
        t=val[i];
        val[i]= val[j];
        val[j] = t;
           permute(i+1,n);
        t=val[i];
        val[i]= val[j];
        val[j] = t; 
        }
    }
}
int main() {
    int T;
    char ch[115];
    int arr[10]={0},i,j;
    long long int N;
    scanf("%d",&T); 
    while(T--)
        {
        N=0;
        for(i=0;i<10;i++)
            arr[i]=0;
        scanf("%s",ch);
        //printf("%s\n",ch);
        //continue;
        for(i=0;i<strlen(ch);i++)
            {
            arr[ch[i]-48]=1;
        }
        j=0;
        for(i=0;i<10;i++)
            {
            //printf("%d ",arr[i]);
            if(arr[i] == 1)
              val[j++] = i; //N = N*10 + i;
        }
        //for(i=0;i<j;i++)
          //printf("%d ",val[i]);
       // break;
        flag = 0;
        //printf("%d\n",flag);
        permute(0,j-1);
        //printf("%d\n",flag);
        if(flag == 1)
            printf("YES\n");
        else
            printf("NO\n");
        //if(arr[0] == 1)
           // N = N*10;        
        //printf(" %lld\n",N);
        //break;    
    }
    return 0;
}

Compile & Run : http://ideone.com/trpXu6
Follow On Twitter : https://twitter.com/codeifucansolve
Follow on Quora : http://codeifyoucansolve.quora.com/Manasa-loves-Maths

Tree Pruning

Given a tree with N vertices numbered from 1 to N. The vertex 1 is the root of the tree. Each vertex is assigned with an integer weight. A remove operation can remove sub-tree rooted at an arbitrary vertex u. You must use at most K remove operations (possibly zero) so that the total weight of the remaining vertices is largest.

Input Format
The first line contains two integers N,K.
The second line contains N integers, the ith integer is the weight of the ith vertex.
Each of the next N−1 lines contains a pair of integers u and v, which represents an edge from vertex u to vertex v.

Output Format
Print out a single integer which is the largest total weight of the remaining vertices.

Constraints
2≤N≤105
1≤K≤200
−109≤weight≤109

Sample Input

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

Sample Output

2

Explanation
We use 2 remove operations: one for the sub-tree rooted at 3 and the other one for the sub-tree rooted at 4. There are only 2 remaining vertices which are 1 and 2. The total weight is 1+1=2.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits

Choose a translation

157 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 100000
long long int k[MAX][200];
    
    int visited[MAX];
int main() {
    long long int N,K,u,w[MAX],v,sum,j,i;
        scanf("%lld%lld",&N,&K);
        i=1;
        while(i<=N)
            {
            scanf("%lld",&w[i]);
            i++;
        }
        i=0;
        sum =   0;
    i=0;
       while(i<N)
            {
           if(i!=0)
               {
            scanf("%lld%lld",&u,&v);
            //if(visited[u] == 0 && visited[v] == 0)
                sum =   w[u] + w[v];
            //else if(visited[u] != 0 && visited[v] == 0)
                //sum  = w[v];
            //else
                //sum  = w[u];
                
            visited[u] =1;
            visited[v] =1;   
           }
            for(j=0;j<=K;j++)
                {
                if(i==0||j==0)
                    k[i][j] = 0;
                else
                    {                    
                    if((sum + k[i-1][j]) > k[i-1][j])
                        k[i][j] = sum + k[i-1][j];
                    /*else if((w[u] + k[i-1][j]) > k[i-1][j])
                        k[i][j] = w[u] + k[i-1][j];
                    else if((w[v] + k[i-1][j]) > k[i-1][j])
                        k[i][j] = w[v] + k[i-1][j];*/ 
                    else
                        k[i][j] =   k[i-1][j];
                }
            }
            i++;
        }
    /*for(i=0;i<N;i++)
        {
        for(j=0;j<=K;j++)
            {
            printf("%d ",k[i][j]);
        }
        printf("\n");
    }*/
        printf("%lld\n",k[N-1][K]);
    return 0;
}

Compile & Run : https://ideone.com/s9dXhs
Follow on : https://twitter.com/codeifucansolve

Reverse Game

Akash and Akhil are playing a game. They have N balls numbered from 0 to N−1. Akhil asks Akash to reverse the position of the balls, i.e., to change the order from say, 0,1,2,3 to 3,2,1,0. He further asks Akash to reverse the position of the balls N times, each time starting from one position further to the right, till he reaches the last ball. So, Akash has to reverse the positions of the ball starting from 0th position, then from 1st position, then from 2nd position and so on. At the end of the game, Akhil will ask Akash the final position of any ball numbered K. Akash will win the game, if he can answer. Help Akash.

Input Format
The first line contains an integer T, i.e., the number of the test cases.
The next T lines will contain two integers N and K.

Output Format
Print the final index in array.

Constraints
1≤T≤50
1≤N≤105
0≤K<N
Sample Input

2
3 1
5 2
Sample Output

2
4
Explanation
For first test case, The rotation will be like this:
0 1 2 -> 2 1 0 -> 2 0 1 -> 2 0 1
So, Index of 1 will be 2.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits
Choose a translation

961 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int T;  
    long int N,K;
    scanf("%d\n",&T);
    while(T--)
        {
        scanf("%ld%ld",&N,&K);
        if(K < (N/2))
            printf("%ld\n",(2*K + 1));
        else
            printf("%ld\n",2*((N-1)-K));
    }
    return 0;
}

Compile & Run : https://ideone.com/a2noJd
Follow On : https://twitter.com/codeifucansolve

Restaurant (GCD)

#codeifyoucansolve
Martha is interviewing at Subway. One of the rounds of the interview requires her to cut a bread of size l×b into smaller identical pieces such that each piece is a square having maximum possible side length with no left over piece of bread.

Input format
The first line contains an integer T. T lines follow. Each line contains two space separated integers l and b which denote length and breadth of the bread.

Output format

T lines, each containing an integer that denotes the number of squares of maximum size, when the bread is cut as per the given condition.

Constraints

1 <= T <= 1000
1 <= l, b <= 1000
Sample Input

2
2 2
6 9
Sample Output

1
6
Explanation

The 1st testcase has a bread whose original dimensions are 2×2, the bread is uncut and is a square. Hence the answer is 1.
The 2nd testcase has a bread of size 6×9. We can cut it into 54 squares of size 1×1, 0 of size 2×2, 6 of size 3×3, 0 of size 4×4, 0 of size 5×5 and 0 of size 6×6. The number of squares of maximum size that can be cut is 6.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits
1946 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int T,L,B,i,area;
    scanf("%d",&T);
    while(T--)
        {
        scanf("%d%d",&L,&B);
        if(L>B)
            i=L;
        else
            i=B;
        while(i>0)
            {
            if(L%i == 0 && B % i == 0)
                {
                area = (L*B)/(i*i);
                break;
            }
            i--;
        }
        printf("%d\n",area);
    }
    return 0;
}

Compile & Run : https://ideone.com/WCZnyH
https://twitter.com/codeifucansolve

Snakes and Ladders: The Quickest Way Up

#codeifyoucansolve
Markov takes out his Snakes and Ladders game and stares at the board, and wonders: If he had absolute control on the die, and could get it to generate any number (in the range 1-6) he desired, what would be the least number of rolls of the die in which he’d be able to reach the destination square (Square Number 100) after having started at the base square (Square Number 1)?

Rules

Markov has total control over the die and the face which shows up every time he tosses it. You need to help him figure out the minimum number of moves in which he can reach the target square (100) after starting at the base (Square 1).

A die roll which would cause the player to land up at a square greater than 100, goes wasted, and the player remains at his original square. Such as a case when the player is at Square Number 99, rolls the die, and ends up with a 5.

If a person reaches a square which is the base of a ladder, (s)he has to climb up that ladder, and he cannot come down on it. If a person reaches a square which has the mouth of the snake, (s)he has to go down the snake and come out through the tail – there is no way to climb down a ladder or to go up through a snake.

Input Format

The first line contains the number of tests, T. T testcases follow.

For each testcase, there are 3 lines.

The first line contains the number of ladders and snakes, separated by a comma.
The second is a list of comma separated pairs indicating the starting and ending squares of the ladders. The first point is the square from which a player can ascend and the second point is his final position.
The third is a list of comma separated pairs indicating the starting and ending (mouth and tail) squares of the snakes. the first point is the position of the mouth of the snake and the second one is the tail.
Multiple comma separated pairs of snakes and ladders are separated by a single space.

Constraints
The board is always of the size 10 x 10
1 <= T <= 10
1 <= Number of Snakes <= 15
1 <= Number of Ladders <= 15
Squares are always numbered 1 to 100 and the order can be seen in the image above.

Output Format

For each of the T test cases, output one integer each on a new line, which is the least number of moves (or rolls of the die) in which the player can reach the target square (Square Number 100) after starting at the base (Square Number 1). This corresponds to the ideal sequence of faces which show up when the die is rolled.

Sample Input

3
3,7
32,62 42,68 12,98
95,13 97,25 93,37 79,27 75,19 49,47 67,17
5,8
32,62 44,66 22,58 34,60 2,90
85,7 63,31 87,13 75,11 89,33 57,5 71,15 55,25
4,9
8,52 6,80 26,42 2,72
51,19 39,11 37,29 81,3 59,5 79,23 53,7 43,33 77,21

Sample Output

3
3
5

Explanation

For the first test: To traverse the board via the shortest route, the player first rolls the die to get a 5, and ends up at square 6. He then rolls the die to get 6. He ends up at square 12, from where he climbs the ladder to square 98. He then rolls the die to get ‘2’, and ends up at square 100, which is the target square. So, the player required 3 rolls of the die for this shortest and best case scenario. So the answer for the first test is 3.

For the second test: Rolls the die to get 1, reaches square 2. Then, climbs the ladder to square 90. Rolls the die to get 4, reaches square 94. Rolls the die to get 6, reaches square 100, which is the target square. So the answer for the second test is also 3.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits
1451 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
inline int get_input()
{
int num=0,sign=1;
char d	=	getchar();
if(d	==	'-')
	sign	=	-1;
while((d<'0'||d>'9')	&&	d!=EOF&&d!='-')
	d	=	getchar();
if(d	==	'-')
	sign	=	-1, d=getchar();
while(d>='0'	&&	d<='9')
{
		num=(num<<3)+(num<<1)+(d-'0');
		d=getchar();
}
	return sign*num;
}
int arr[101];
int main() {
    int T,L,K,i,j,m,u,v,min,count;
    scanf("%d",&T);
    while(T--)
    {
        L=get_input();
        K=get_input();
        m=L;
        while(L--)
            {
            u=get_input();
            v=get_input();
            arr[u]=v;
        }
        while(K--)
            {
            u=get_input();
            v=get_input();
            arr[u]=v;
        }
        min=32767;
        while(m--)
        { 
         count = 0;
        for(i=1;i<=100;)
            {
            for(j=i+1;j<(i+7);j++)
                {
                if(arr[j]>j)
                    {
                    v=arr[j];
                    arr[j] = 0;
                    j=v;
                    break;
                }
                if(arr[j]<j)
                    {
                    if(j==i+6)
                        {
                        i=i-1;
                        break;
                    }
                    continue;
                }
            }
            count +=1;
            i=j; 
        }
         if(min>count)
             min = count;
        }
        printf("%d\n",min);

    }
    return 0;
}

Compile & Run : https://ideone.com/oBddkJ
Follow On : https://twitter.com/codeifucansolve

Even Tree

You are given a tree (a simple connected graph with no cycles). You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest should contain an even number of vertices.

To accomplish this, you will remove some edges from the tree. Find out the number of removed edges.

Input Format
The first line of input contains two integers N and M. N is the number of vertices and M is the number of edges.
The next M lines contain two integers ui and vi which specifies an edge of the tree. (1-based index)

Output Format
Print the answer, a single integer.

Constraints
2 <= N <= 100.

Note: The tree in the input will be such that it can always be decomposed into components containing even number of nodes.

Sample Input

10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8

Sample Output

2

Explanation
On removing edges (1, 3) and (1, 6), we can get the desired result.

Original tree:

Decomposed tree:

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits
5099 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 100
typedef struct graph
    {
  int v;
  struct graph *e;  
}graph;
int visited[101];
int bfs[101];
int main() {
    int N,M,ui,vi,i,l,c,chld[101]={0},vrtx;
    graph *g[MAX],*next;
    scanf("%d%d",&N,&M);
    i=1;
    while(i<=N)
        {
        g[i]=(graph *)malloc(sizeof(graph));
        g[i]->v=i;
        g[i]->e=NULL;
        i++;
    }
    i=0;
    while(i<M)
        {
        scanf("%d%d",&ui,&vi);
        next=g[ui];
        while(next->e!=NULL)
            next=next->e;
        next->e = (graph *)malloc(sizeof(graph));
            next->e->v=vi;
            next->e->e=NULL;
        next=g[vi];
        while(next->e!=NULL)
            next=next->e;
        next->e = (graph *)malloc(sizeof(graph));
            next->e->v=ui;
            next->e->e=NULL;        
        i++;
    }
    i=0;
    l=1;
    bfs[0]=1;
    visited[0]=1;
    while(i<N)
        {
            next = g[bfs[i]];
            visited[next->v] = 1;
            chld[next->v] = 1;
                next=next->e;        
            while(next!=NULL)
                {
                if(visited[next->v] == 0)
                {
                   bfs[l++]=next->v;
                   chld[next->v] =1;
                }
                next=next->e;                
            }
        i++;
    }
    i=N-1;
    while(i>=0)
        {
            next = g[bfs[i]];
            visited[next->v] = 0;
            vrtx = next->v;
            next=next->e; 
        l=0;
            while(next!=NULL)
                {
                if(visited[next->v] == 1)
                {
                   chld[next->v] += chld[vrtx];                
                   l += 1;
                }
                next=next->e;                
            }
        if(l==0)
            chld[vrtx] -= 1;
        i--;
    }
    c=0;
    for(i=1;i<=N;i++)
        {
        if(chld[i] % 2 == 0)
            c+=1;  
    }
    printf("%d\n",c);
    return 0;
}

Compile and Run : http://ideone.com/VT1cZM
Follow On : https://twitter.com/codeifucansolve

Eugene and Big Number

Eugene must do his homework, but he is struggling.
He has three integer numbers: A, N, M. He writes number A on the board N times in a row. Let’s call the resulting big number X. Help Eugene find X modulo M.

Input Format

First line contains T, the number of testcases.
Each testcase contains three numbers: A, N, M separated by a single space.

Constraints
1 <= T <= 200
0 <= A <= 1000 (1e3)
0 < N < 1000000000000 (1e12)
1 < M < 1000000000 (1e9)

Output Format

Print the required answer for each testcase in a new line.

Sample Input

2
12 2 17
523 3 11

Sample Output

5
6

Explanation

First testcase:
A = 12
N = 2
X = 1212
1212 modulo 17 = 5

Second testcase:
A = 523
N = 3
X = 523523523
523523523 modulo 11 = 6

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int T,A,tn;
    long long int N,M,num;
    scanf("%d",&T);
    while(T--)
        {
        tn=10;
        scanf("%d%lld%lld",&A,&N,&M);
        num=A/10;
        while(num>0)
        {
            tn=tn*10;
            num=num/10;
        }
        //printf("%d\n",tn);
        num = A%M;
        N=N-1;
        while(N--)
            {
            num = (num*tn + A)%M;
        }
        printf("%lld\n",num);
    }
    return 0;
}

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

Find Maximum Index Product

You are given a list of n numbers a1,a2,…,an. For each i (1≤i≤n), define LEFT(i) to be the nearest index j before i such that aj>ai. Note that if j does not exist, we should consider LEFT(i) to be 0. Similarly, define RIGHT(i) to be the nearest index j after i such that aj>ai. Note that if j does not exist, we should consider RIGHT(i) to be 0.

Define INDEXPRODUCT(i) as the product of LEFT(i) and RIGHT(i). Find the maximum INDEXPRODUCT(i) among all 1≤i≤n.

Input Format

The first line contains an integer n, the number of integers. The next line contains the N integers.

Constraints:

1≤N≤105

Each of the N integers will range from 0 to 109

Output Format

Output the maximum INDEXPRODUCT among all indices from 1 to N.

Sample Input

5
5 4 3 4 5

Sample Output

8

Explanation

We can compute the following:

INDEXPRODUCT(1)=0
INDEXPRODUCT(2)=1×5=5
INDEXPRODUCT(3)=2×4=8
INDEXPRODUCT(4)=1×5=5
INDEXPRODUCT(5)=0

The largest of these is 8, so it is the answer

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
  long int n,arr[100000],i,l,r;
    long long int max=0,max_p=0;
    scanf("%ld",&n);
    for(i=0;i<n;i++)
        {
        scanf("%ld",&arr[i]);
    }
    for(i=1;i<(n-1);i++)
        {
        l=i-1;
        while(l>=0)
            {
            if(arr[l]>arr[i])
                break;
            l--;
        }
        if(arr[l]>arr[i])
            l = l+1;
        else
            l=0;
        r=i+1;
        while(r<n)
            {
            if(arr[r]>arr[i])
                break;
            r++;
        }
        if(r==n)
            r=0;
        else
            r=r+1;
        max_p = l*r;
        if(max_p>max)
            max=max_p;
    }
    printf("%lld",max);
    return 0;
}

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

Funny String

Suppose you have a string S which has length N and is indexed from 0 to N−1. String R is the reverse of the string S. The string S is funny if the condition |Si−Si−1|=|Ri−Ri−1| is true for every i from 1 to N−1.

(Note: Given a string str, stri denotes the ascii value of the ith character (0-indexed) of str. |x| denotes the absolute value of an integer x)

Input Format

First line of the input will contain an integer T. T testcases follow. Each of the next T lines contains one string S.

Constraints

1<=T<=10
1<=length of S<=10000

Output Format

For each string, print Funny or Not Funny in separate lines.

Sample Input

2
acxz
bcxz

Sample Output

Funny
Not Funny

Explanation

Consider the 1st testcase acxz

here

|c-a| = |x-z| = 2
|x-c| = |c-x| = 21
|z-x| = |a-c| = 2

Hence Funny.

Consider the 2st testcase bcxz

here

|c-b| != |x-z|

Hence Not Funny.

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

int main() {
 
    int T,i,j,flag=0;
    char s[10000];
    scanf("%d",&T);
    while(T--)
        {
        scanf("%s",s);
        i=0;j=strlen(s) -1;
        flag = 0;
        for(;i<=j;)
            {
            if(abs(s[i]-s[i+1]) != abs(s[j]-s[j-1]))
                {
                flag    =   1;
                break;
            }
            i+=2;j-=2;
        }
        if(flag==1)
            printf("Not Funny\n");
        else
            printf("Funny\n"); 
    }
    return 0;
}

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