You are on page 1of 221

ADA PROGRAMS

Q. 1: Missing element of AP
QUESTION DESCRIPTION

Find the missing element from an ordered array A[ ], consisting of N elements representing an Arithmetic
Progression (AP) .

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
The first line of each test case contains an integer N, where N is the size of the array A[ ].
The second line of each test case contains N space separated integers of an Arithmetic Progression denoting
elements of the array A[ ].

Note: The series should have a missing element in between a perfect A.P. with no missing element will not be
considered.

Output:
Print out the missing element.

Constraints:
1 <= T <= 100
2 <= N <= 10
-50 <= A[i] <=50
TEST CASE 1

INPUT
3
3
2 10 14
4
-28 -21 -7 0
5
9 12 15 21 24
OUTPUT
6
-14
18
TEST CASE 2

INPUT
3
4
5 8 14 17
3
-21 7 14
5
9 12 15 21 24
OUTPUT
11
-14
18

#include<iostream>

using namespace std;

int main() {

//code

int t;

cin>>t;

while(t--)

int n;

cin>>n;

int a[n];

if(n==2)

int a,b;

cin>>a>>b;

int ans=(a+b)/2;

cout<<ans<<endl;

else if(n>2)

long int sum=0,res;

for(int i=0;i<n;i++)

cin>>a[i];

sum+=a[i];
}

res=((n+1)*(a[0]+a[n-1]))/2;

cout<<(res-sum)<<endl;

return 0;

SESSION: Searching Techniques


Q. 2: Searching 6
QUESTION DESCRIPTION

Given an array of distinct elements. The task is to find triplets in array whose sum is zero. Take the array as
input.
TEST CASE 1

INPUT
0 -1 2 -3 1
OUTPUT
0 -1 1
2 -3 1
TEST CASE 2

INPUT
1 -2 1 0 5
OUTPUT
1 -2 1

#include <iostream>

using namespace std;

int main() {

int a[50];

int i;

for(i=0;i<5;i++)

cin>>a[i];

for(i=0;i<5;i++)

for(int j=i+1;j<5;j++)
for(int k=j+1;k<5;k++)

if(a[i]+a[j]+a[k]==0)

cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<"\n";

}
SESSION: Searching Techniques
Q. 3: Address
QUESTION DESCRIPTION

You have to find the address and mobile number of the employee in the company you have to go through
employee details register and find his/her mobile number
TEST CASE 1

INPUT
2
Williams
9851552422
Chennai
Milton
9532452525
Chennai

Williams
OUTPUT
Name Mobile Number City
Williams 9851552422 Chennai
TEST CASE 2

INPUT
2
Williams
9851552422
Chennai
Milton
9532452525
Chennai

#include <iostream>

#include <string.h>

using namespace std;

int main()

int n;

char name[10][20],ad[10][20];
long num[10];

cin>>n;

for(int i=0; i<n; i++)

cin>>name[i];

cin>>num[i];

cin>>ad[i];

char na[20];

cin>>na;

int flag=0;

for(int i=0; i<n; i++)

if(strcmp(na,name[i])==0)

cout<<"Name Mobile Number City";

cout<<"\n"<<name[i]<<" "<<num[i]<<" "<<ad[i];

flag=1;

break;

if(flag==0)

cout<<"The Entered Name is not in the Directory";

return 0;

}
SESSION: Searching Techniques
Q. 4: Third largest element
QUESTION DESCRIPTION

Given an array of distinct elements, find third largest element in it.


Take the number of elements and the array as input.
TEST CASE 1

INPUT
6
1 14 2 16 10 20
OUTPUT
The third Largest element is 14
TEST CASE 2

INPUT
7
19 -10 20 14 2 16 10
OUTPUT
The third Largest element is 16
Problem with Question? Report

#include <iostream>

using namespace std;

int main() {

int n,c,i,j;

cin>>n;

int arr[50];

for(i=0;i<n;i++)

cin>>arr[i];

for(i=0;i<n;i++)

for(j=i+1;j<n;j++)

if (arr[j]<arr[i])

c=arr[i];
arr[i]=arr[j];

arr[j]=c;

cout<<"The third Largest element is "<<arr[n-3];

return 0;

Q. 5: Faculty
QUESTION DESCRIPTION

HoD have to find the mobile number of the faculty. HoD have to go through the faculty list that will be
arranged according to the year of entry.
TEST CASE 1

INPUT
3
Rahul 9598454222 2015
Ashwin 7501202255 2010
Saleem 8545222522 2012
Asha
OUTPUT
The Entered Name is not in the Directory
TEST CASE 2

INPUT
3
Rahul 9598454222 2015
Ashwin 7501202255 2010
Saleem 8545222522 2012
Rahul
OUTPUT
Name TelephoneNumber Year
Rahul 9598454222 2015

#include <iostream>

#include <string.h>

using namespace std;

int main()
{

int n;

char name[10][20];

long num[10];

int yr[10];

cin>>n;

for(int i=0; i<n; i++)

cin>>name[i];

cin>>num[i];

cin>>yr[i];

char na[20];

cin>>na;

int flag=0;

for(int i=0; i<n; i++)

if(strcmp(na,name[i])==0)

cout<<"Name TelephoneNumber Year";

cout<<"\n"<<name[i]<<" "<<num[i]<<" "<<yr[i];

flag=1;

break;

if(flag==0)

cout<<"The Entered Name is not in the Directory";


return 0;

Q. 6: Highest Mark
QUESTION DESCRIPTION

The DS teacher wants to know the student of second highest mark in CT 1, if she has a ordered list of marks
for 10 students.
TEST CASE 1

INPUT
Thomas 75
Imran 60
Sithik 55
Setan 80
Milton 85
Arjun 90
Rakesh 91
Hrithik 88
Ayush 72
Aswathy 96
OUTPUT
Ordered List
Aswathy 96
Rakesh 91
Arjun 90
Hrithik 88
Milton 85
Setan 80
Thomas 75
Ayush 72
Imran 60
Sithik 55
Second Highest mark is 91
TEST CASE 2

INPUT
Thomas 75
Imran 60
Sithik 10
Setan 80
Milton 85
Arjun 90
Rakesh 91
Hrithik 88
Ayush 72
Aswathy 55
OUTPUT
Ordered List
Rakesh 91
Arjun 90
Hrithik 88
Milton 85
Setan 80
Thomas 75
Ayush 72
Imran 60
Aswathy 55
Sithik 10
Second Highest mark is 90

#include <iostream>

#include <string>

using namespace std;

class Student {

public:

string name;

int marks;

void set() {

cin >> name >> marks;

void print() {

cout << name << " " << marks << endl;

int getMarks() {

return marks;

};

int main()

Student pupils[10];

for (int i = 0; i < 10; i++) pupils[i].set();

for (int i = 0; i < 10; i++){


for (int j = i; j < 10; j++){

if (pupils[i].marks < pupils[j].marks) {

Student temp = pupils[i];

pupils[i] = pupils[j];

pupils[j] = temp;

cout << "Ordered List\n";

for (int i = 0; i < 10; i++) pupils[i].print();

cout << "Second Highest mark is " << pupils[1].getMarks();

return 0;

SESSION: Searching Techniques


Q. 7: Searching 1
QUESTION DESCRIPTION

Find three closest elements from given three sorted arrays. Take the three sorted arrays and their sizes as input.
TEST CASE 1

INPUT
3
1 4 10
3
2 15 20
2
10 12
OUTPUT
10 15 10
TEST CASE 2

INPUT
3
20 24 100
5
2 19 22 79 800
5
10 12 23 24 119
OUTPUT
24 22 23
#include <iostream>

#include <algorithm>

using namespace std;

int main()

int p,q,r,i,j,k,res_i,res_j,res_k,diff=9999;

cin>>p;

int a[p];

for(i=0;i<p;i++)

cin>>a[i];

cin>>q;

int b[q];

for(j=0;j<q;j++)

cin>>b[j];

cin>>r;

int c[r];

for(k=0;k<r;k++)

cin>>c[k];

//Get the closest elements

for(i=0,j=0,k=0;i<p && j<q && k<r;){

int mini=min(a[i],min(b[j],c[k]));

int maxi=max(a[i],max(b[j],c[k]));

if(maxi-mini<diff){

diff=maxi-mini;

res_i=i;res_j=j;res_k=k;
}

if(a[i]==mini)

i++;

else if(b[j]==mini)

j++;

else

k++;

cout<<a[res_i]<<" "<<b[res_j]<<" "<<c[res_k];

return 0;

}
Q. 8: Search in a matrix
QUESTION DESCRIPTION

Given an n x m matrix, where every row and column is sorted in increasing order, and a number x .

The task is to find whether element x is present in the matrix or not.

Expected Time Complexity : O(m + n)

Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow.
Each test case consists of three lines.
First line of each test case consist of two space separated integers N and M, denoting the number of element in
a row and column respectively.
Second line of each test case consists of N*M space separated integers denoting the elements in the matrix in
row major order.
Third line of each test case contains a single integer x, the element to be searched.

Output:

Corresponding to each test case, print in a new line, 1 if the element x is present in the matrix, otherwise
simply print 0.

Constraints:
1<=T<=200
1<=N,M<=30
TEST CASE 1

INPUT
2
3 3
3 30 38 44 52 54 57 60 69
62
1 6
18 21 27 38 55 67
55
OUTPUT
0
1
TEST CASE 2

INPUT
2
3 2
2 16 18 20 25 30
60
4 3
2 30 49 56 57 64 20 10 34 54 63 72
68
OUTPUT
0
0

#include <iostream>

using namespace std;

int main() {

int n,i,j,x;

cin>>n;

for(i=0;i<n;i++)

int a,b,arr[50];

cin>>a>>b;

int c;

c=a*b;

for(j=0;j<c;j++)

cin>>arr[j];

}
int test;

cin>>test;

for(j=0;j<c;j++)

if(arr[j]==test)

x=1;

if(x==1)

cout<<"1\n";

else

cout<<"0\n";

return 0;

SESSION: Searching Techniques


Q. 9: Linear List
QUESTION DESCRIPTION

The DS Faculty wants to know number of students got pass mark in CT I if she has a unordered list of marks
for 10 students
TEST CASE 1

INPUT
Thomas 75
Imran 60
Sithik 80
Setan 80
Milton 85
Arjun 25
Rakesh 91
Hrithik 88
Ayush 45
Aswathy 55
OUTPUT
Number of the student got pass marks 8
TEST CASE 2

INPUT
Thomas 75
Imran 60
Sithik 80
Setan 80
Milton 85
Arjun 55
Rakesh 91
Hrithik 88
Ayush 85
Aswathy 55
OUTPUT
Number of the student got pass marks 10

#include <iostream>

#include<string>

using namespace std;

int main() {

int m[50],x=0,i;

string n[50];

for(i=0;i<10;i++)

cin>>n[i];

cin>>m[i];

for(i=0;i<10;i++)

{
if(m[i]>=50)

x=x+1;

cout<<"Number of the student got pass marks "<<x;

return 0;

Q. 10: Alice Question


QUESTION DESCRIPTION

10 Students have randomly requested to Ms.Alice for subject DS allocated with roll no from 1 to 30 randomly
.If Alice want to find roll no:5 belongs to her or not? Help her.
TEST CASE 1

INPUT
1 2 3 4 15 6 7 8 9 10
OUTPUT
Roll no 5 not belongs to Ms.Alice Class
TEST CASE 2

INPUT
8 4 6 2 7 5 1 6 14 12
OUTPUT
Roll no 5 belongs to Ms.Alice Class
Problem with Question? Report

#include <iostream>

using namespace std;

int main() {

int st[50],x=0,i;

for(i=0;i<10;i++)

cin>>st[i];

}
for(i=0;i<10;i++)

if(st[i]==5)

x=1;

if(x==1)

cout<<"Roll no 5 belongs to Ms.Alice Class";

else

cout<<"Roll no 5 not belongs to Ms.Alice Class";

return 0;

SESSION: Sorting Techniques


Q. 11: Number of pairs
QUESTION DESCRIPTION

Given two arrays X[ ] and Y[ ] of positive integers, find number of pairs such that x^y > y^x where x is an
element from X[ ] and y is an element from Y[ ].

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each
test consists of three lines.
The first line of each test case consists of two space separated M and N denoting size of arrays X[ ] and Y[ ]
respectively.
The second line of each test case contains M space separated integers denoting the elements of array X[ ].
The third line of each test case contains N space separated integers denoting elements of array Y[ ].

Output:

Corresponding to each test case, print in a new line, the number of pairs such that x^y > y^x.

Constraints:

1 <= T <= 100


1 <= M,N <= 200
1 <= X[i],Y[i] <= 500
TEST CASE 1

INPUT
1
3 2
2 1 6
1 5
OUTPUT
3
TEST CASE 2

INPUT
1
3 2
5 2 4
5 1
OUTPUT
5

#include<math.h>

#include <iostream>

using namespace std;

int main() {

int n,ans=0,i,j,k,x,y;

cin>>n;

for(i=0;i<n;i++)

int a,b;

cin>>a>>b;

int q[50],w[50];

for(j=0;j<a;j++)

cin>>q[j];

for(j=0;j<b;j++)

{
cin>>w[j];

for(j=0;j<a;j++)

for(k=0;k<b;k++)

x=pow(q[j],w[k]);

y=pow(w[k],q[j]);

if(x>y)

ans=ans+1;

cout<<ans;

return 0;

Q. 12: Faculty Details


QUESTION DESCRIPTION

There are faculties in the department, you have to arrange the list of faculties depending upon ID numbers.
TEST CASE 1

INPUT
5
Ram 101
Rahul 95
Ashwin 75
Ahamed 106
Saurav 110
OUTPUT
After Sorting
Name ID
Ashwin 75
Rahul 95
Ram 101
Ahamed 106
Saurav 110
TEST CASE 2

INPUT
3
Ram 101
Rahul 95
Ashwin 75
OUTPUT
After Sorting
Name ID
Ashwin 75
Rahul 95
Ram 101

#include <iostream>

using namespace std;

struct fac

char name[100];

int id;

};

int main()

struct fac s[100],temp;

int i,j,n;

cin>>n;

for(i=0;i<n;i++)

cin>>s[i].name>>s[i].id;

for(i=0;i<=n-1;i++)

{
for(j=0;j<=n-1;j++)

if(s[j].id>s[j+1].id)

temp=s[j];

s[j]=s[j+1];

s[j+1]=temp;

cout<<"After Sorting\n";

cout<<"Name ID\n";

for(j=1;j<=n;j++)

cout<<s[j].name<<" "<<s[j].id<<"\n";

return 0;

Q. 13: Sort by Set Bit Count


QUESTION DESCRIPTION

Given an array of integers, sort the array (in descending order) according to count of set bits in binary
representation of array elements.

For integers having same number of set bits in their binary representation, sort according to their position in
the original array i.e., a stable sort.

For example, if input array is {3, 5}, then output array should also be {3, 5}. Note that both 3 and 5 have same
number set bits.

Input: arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32};


Output: 15 7 5 3 9 6 2 4 32

Input:

The first line of input contains an integer T denoting the number of test cases. The description of T test cases
follows.

The first line of each test case contains a single integer N denoting the size of array. The second line contains
N space-separated array elements.

Output:

Print each sorted array in a seperate line. For each array its numbers should be seperated by space.

Constraints:

1<= T <= 1000


0 <= N <= 100000
1 <= A[i] <= 1000000

TEST CASE 1

INPUT
2
3
3 1 5
4
5 16 6 15
OUTPUT
3 5 1
15 5 6 16
TEST CASE 2

INPUT
3
2
6 5
5
15 1 61 24 10
2
7 9
OUTPUT
6 5
61 15 24 10 1
7 9

#include <iostream>

using namespace std;

int countBits(int a)

int count=0;

while(a)
{

if(a&1)

count+=1;

a=a>>1;

return count;

void insertionSort(int arr[],int aux[],int n)

for (int i=1;i<n;i++)

int key1=aux[i];

int key2=arr[i];

int j=i-1;

while((j>=0)&&(aux[j]<key1))

aux[j+1]=aux[j];

arr[j+1]=arr[j];

j=j-1;

aux[j+1]=key1;

arr[j+1]=key2;

void sortBySetBitCount(int arr[],int n)

{
int aux[n];

for (int i=0;i<n;i++)

aux[i]=countBits(arr[i]);

insertionSort(arr,aux,n);

void printArr(int arr[],int n)

for (int i=0;i<n;i++)

if(i!=n-1)

cout<<arr[i]<<" ";

else

cout<<arr[i];

cout<<endl;

int main()

int arr[10],tc,i,j,num;

cin>>tc;

for(i=0;i<tc;i++)

cin>>num;
for(j=0;j<num;j++)

cin>>arr[j];

sortBySetBitCount(arr,num);

printArr(arr,num);

return 0;

Q. 14: Shop in Candy Store


QUESTION DESCRIPTION

In a candy store there are N different types of candies available and the prices of all the N different types of
candies are provided to you.
You are now provided with an attractive offer.
You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free.
Now you have to answer two questions. Firstly, you have to tell what is the minimum amount of money you
have to spend to buy all the N different candies. Secondly, you have to tell what is the maximum amount of
money you have to spend to buy all the N different candies.
In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free.

Input

The first line of the input contains T the number of test cases. Each test case consists of two lines.
The first line of each test case contains the values of N and K as described above. Then in the next line N
integers follow denoting the price of each of the N different candies.

Output

For each test case output a single line containing 2 space separated integers , the first denoting the minimum
amount of money required to be spent and the second denoting the maximum amount of money to be spent.
Remember to output the answer of each test case in a new line.

Constraints
1 <= T <= 50
1 <= N <= 1000
0 <= K <= N-1
1 <= Ai <= 100

Expected Time Complexity : O(nlogn)


TEST CASE 1

INPUT
1
4 2
3 2 1 4
OUTPUT
3 7
TEST CASE 2

INPUT
2
6 2
5 4 2 6 1 8
9 4
2 7 1 6 8 3 12 10 11
OUTPUT
3 14
3 23

#include <iostream>

#include<algorithm>

using namespace std;

int findMoney(int a[],int n,int k)

int x=0,y=n-1,sum=0;

while(x<=y)

sum+=a[x];

y=max(x,y-k);

x++;

return sum;

int main()

int i,n,k,t;

cin>>t;
while(t--)

cin>>n>>k;

int a[n];

for(i=0;i<n;i++)

cin>>a[i];

sort(a,a+n);

cout<<findMoney(a,n,k)<<" ";

sort(a,a+n,greater<int>());

cout<<findMoney(a,n,k)<<"\n";

return 0;

SESSION: Sorting Techniques


Q. 15: Decode the string
QUESTION DESCRIPTION

An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as
follows
original string: abbbababbbababbbab
TEST CASE 1

INPUT
2
1[b]
3[b2[ca]]
OUTPUT
b
bcacabcacabcaca
TEST CASE 2

INPUT
2
2[a]
2[c1[bc]]
OUTPUT
aa
cbccbc

#include<iostream>
#include<stack>

using namespace std;

bool isDigit(char ch)

return(ch>='0'&& ch<='9');

int main()

int T;

cin>>T;

while(T--)

string str;

cin>>str;

stack<int>s1;

stack<char>s2;

string ans="";

for(int i=0;i<str.length();i++)

char c=str.at(i);

if(isDigit(c))

int temp=0;

while(isDigit(str.at(i)))

temp=10*temp+str.at(i)-'0';

i++;

s1.push(temp);
i--;

else if(c=='[')

s2.push(c);

else if (c==']')

string temp1="";

while(s2.top()!='[')

temp1=s2.top()+temp1;

s2.pop();

s2.pop();

int temp=s1.top();

s1.pop();

string temp3="";

for(int i=0;i<temp;i++)

temp3=temp3+ "" + temp1;

for(int i=0;i<temp3.length();i++)

s2.push(temp3.at(i));

else

{
s2.push(c);

while(!s2.empty())

ans=ans+"" +s2.top();

s2.pop();

for(int i=ans.length()-1;i>=0;i--)

cout<<ans.at(i);

cout<<endl;

return 0;

}
Q. 16: Scoring in Exam
QUESTION DESCRIPTION

Milly is at the examination hall where she is reading a question paper. She checked the question paper and
discovered that there are N questions in that paper. Each question has some score value. Ideally it's like
questions requiring more time have more score value and strangely no two questions on the paper require same
time to be solved.

She is very excited by looking these questions. She decided to solve K questions while maximizing their score
value. Could you please help Milly to determine the exact time she needs to solve the questions.

Input

First line of input contains two space separated integers N and Q, where N is the number of questions available
and Q is number of queries
Next line contains N space separated integers denoting the time Ti of N questions
Next line contains N space separated integers denoting the scores Si of N questions
Next Q lines contains a number K each, the number of questions she wants to solve
Output

Print the time required for each query in a separate line.


Constraints
1 <= N <= 105
1 <= Q <= 105
1 <= K <= N
1 <= Ti, Si <= 109
TEST CASE 1

INPUT
5 2
2 3 9 4 5
3 5 11 6 7
5
3
OUTPUT
23
18
TEST CASE 2

INPUT
6 4
3 5 1 7 4 2
5 7 3 9 6 4
5
2
4
6
OUTPUT
21
12
19
22

#include <stdio.h>

#include <stdlib.h>

typedef int (*compfn)(const void*, const void*);

struct exam { long time_ ;

long marks;

};

void printarray(void);
int compare(struct exam *, struct exam *);

int main(void)

long n,queries,ques;

long i,j;

scanf("%ld%ld",&n,&queries);

struct exam array[n] ;

for(i=0;i<n;i++)

scanf("%ld",&(array[i].time_));

for(i=0;i<n;i++)

scanf("%ld",&(array[i].marks));

qsort((void *) &array, // Beginning address of array

n, // Number of elements in array

sizeof(struct exam), // Size of each element

(compfn)compare ); // Pointer to compare function

for(j=1;j<n;j++)

array[j].time_+=array[j-1].time_;

for(i=0;i<queries;i++)
{ scanf("%ld",&ques);

printf("%ld\n",array[--ques].time_);

return 0;

int compare(struct exam *elem1, struct exam *elem2)

if ( elem1->marks > elem2->marks)

return -1;

else if (elem1->marks < elem2->marks)

return 1;

else

return 0;

SESSION: Sorting Techniques


Q. 17: Insertion sort
QUESTION DESCRIPTION

Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a
computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often
used to introduce the study of algorithms.

Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an
already sorted list.

Insert element into sorted list

Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into
the array so that it remains sorted?

Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge
is to follow the correct order of insertion sort.
Guideline: You can copy the value of e to a variable and consider its cell "empty". Since this leaves an extra
cell empty on the right, you can shift everything over until v can be inserted. This will create a duplicate of
each value, but when you reach the right spot, you can replace it with e .

Input Format

There will be two lines of input:


size - the size of the array
Arr - the unsorted array of integers

Output Format
On each line, output the entire array every time an item is shifted in it.

Constraints

1<=size<=1000
-10000<=e<=10000, e belongs to arr
TEST CASE 1

INPUT
5
2 4 6 8 3
OUTPUT
2 4 6 8 3
2 4 6 8 3
2 4 6 8 3
2 3 4 6 8
TEST CASE 2

INPUT
5
1 0 0 0 2
OUTPUT
0 1 0 0 2
0 0 1 0 2
0 0 0 1 2
0 0 0 1 2

#include <iostream>

using namespace std;

int main() {

int i,n,a[50],j,k,temp;

cin>>n;

for(i=0;i<n;i++)

cin>>a[i];
}

for(i=1;i<n;i++)

temp=a[i];

j=i-1;

while((temp<a[j]) && (j>=0))

a[j+1]=a[j];

j=j-1;

a[j+1]=temp;

for(k=0;k<n;k++)

cout<<a[k]<<" ";

cout<<"\n";

return 0;

}
Q. 18: Sorting Elements of an Array by Frequency
QUESTION DESCRIPTION

Given an array of integers, sort the array according to frequency of elements. For example, if the input array is
{2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.

If frequencies of two elements are same, print them in increasing order.

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases
follows.
The first line of each test case contains a single integer N denoting the size of array. The second line contains
N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:

Print each sorted array in a seperate line. For each array its numbers should be seperated by space.

Constraints:

1 <= T <= 70
30 <= N <= 130
1 <= A [ i ] <= 60
TEST CASE 1

INPUT
1
5
5 4 5 4 6
OUTPUT
4 4 5 5 6
TEST CASE 2

INPUT
2
6
1 2 3 2 1 5
8
2 22 3 6 55 22 1 3
OUTPUT
1 1 2 2 3 5
3 3 22 22 1 2 6 55

#include<stdio.h>

int main()

int t;

scanf("%d",&t);

while(t--)

int i,n;

scanf("%d",&n);
int a[n],p;

for(i=0;i<n;i++)

scanf("%d",&a[i]);

int h[61]={0};

for(i=0;i<n;i++)

h[a[i]]++;

int j,l;

for(i=0;i<61;i++)

int max=0;

for(j=0;j<61;j++)

if(h[j]>max)

max=h[j];

l=j;

for(p=0;p<max;p++)

printf("%d ",l);

h[l]=0;

printf("\n");

return 0;

}
SESSION: Sorting Techniques
Q. 19: Drive the car
QUESTION DESCRIPTION

Suppose you are car driver and you have to drive a car on a track divided into "N" no. of sub-tracks. You are
also given the value of "K" i.e. the total kilometers a car can drive on each sub-track.

If the car can't cover a sub-track, you can add any unit of Petrol in it. With each unit of petrol added, the total
kilometers your car can travel will increase by one unit .

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test
case contains two space separated integers N and K. The second line of each test case contains N space
separated integers (A[]) denoting the distance of each N sub-tracks.

Output:

For each test case in a new line you have to print out the minimum unit of Petrol your car require to cover all
the sub-tracks. If no extra unit of petrol is required, print -1.

Constraints:
1<=T<=100
1<=N,K<=200
1<=A[]<=1000
TEST CASE 1

INPUT
2
5 7
2 5 4 5 2
5 4
1 6 3 5 2
OUTPUT
-1
2
TEST CASE 2

INPUT
1
5 7
2 5 4 5 2
OUTPUT
-1

#include <stdio.h>

int main()

int t,n,k,a[100],max,petrol,i;

scanf("%d",&t);

while(t>0)
{

scanf("%d %d ",&n,&k);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

max=a[0];

for(i=0;i<n;i++)

if(a[i]>max)

max=a[i];

petrol=max-k;

if(petrol<0)

printf("-1\n");

else if(petrol>0)

printf("%d\n",petrol);

t--;

return 0;

Q. 20: Find all four sum numbers


QUESTION DESCRIPTION

Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given
value K. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is 3 5 7 8
(3 + 5 + 7 + 8 = 23).

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test
case contains two lines. The first line of input contains two integers N and K. Then in the next line are N space
separated values of the array.

Output:
For each test case in a new line print all the quadruples present in the array separated by space which sums up
to value of K. Each quadruple is unique which are separated by a delimeter "$" and are in increasing order.

Constraints:
1<=T<=100
1<=N<=100
-1000<=K<=1000
-100<=A[]<=100
TEST CASE 1

INPUT
2
5 3
0 0 2 1 1
7 23
10 2 3 4 5 7 8
OUTPUT
0 0 1 2 $0 0 1 2 $
2 3 8 10 $2 4 7 10 $3 5 7 8 $
TEST CASE 2

INPUT
1
5 3
0 0 2 1 1
OUTPUT
0 0 1 2 $0 0 1 2 $

#include <iostream>

using namespace std;

int main()

int test;
cin>>test;

while(test>0)

int n,sum;

cin>>n>>sum;

int arr[n];

for(int i=0;i<n;i++)

cin>>arr[i];

int temp=0;

for(int i=0;i<n;i++)

for(int j=0;j<n-i-1;j++)

if(arr[j]>arr[j+1])

temp=arr[j+1];

arr[j+1]=arr[j];

arr[j]=temp;

for(int i=0;i<n-3;i++)

for(int j=i+1;j<n-2;j++)

for(int k=j+1;k<n-1;k++)

for(int m=k+1;m<n;m++)
{

if((arr[i]+arr[j]+arr[k]+arr[m])==sum)

cout<<arr[i]<<" "<<arr[j]<<" "<<arr[k]<<" "<<arr[m]<<" $";

cout<<endl;

test--;

return 0;

}
Q. 21: Counting Triangles
QUESTION DESCRIPTION

You are given n triangles.

You are required to find how many triangles are unique out of given triangles. For each triangle you are given
three integers a,b,c , the sides of a triangle.

A triangle is said to be unique if there is no other triangle with same set of sides.

Note : It is always possible to form triangle with given sides.

INPUT:

First line contains n, the number of triangles. Each of next n lines contain three integers a,b,c (sides of a
triangle).

Output:

print single integer, the number of unique triangles.

Constraints:

1 <= n <= 10^5


1 <= a,b,c <= 10^15
TEST CASE 1

INPUT
3
1 2 3
2 3 4
2 4 3
OUTPUT
1
TEST CASE 2

INPUT
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
OUTPUT
1

#include <bits/stdc++.h>

using namespace std;

int main()

long long n,a,b,c;

cin>>n;

map<string,int>M;

while(n--)

cin>>a>>b>>c;

vector<int> vec;

vec.push_back(a);

vec.push_back(b);

vec.push_back(c);

sort(vec.begin(),vec.end());

a=vec[0];

b=vec[1];

c=vec[2];
M[to_string(a)+','+to_string(b)+','+to_string(c)]++;

int cnt=0;

for(auto it:M)

{ if(it.second==1)

cnt++;

cout<<cnt;

return 0;

Q. 22: Minimum and Maximum


QUESTION DESCRIPTION

Divide the problem into a number of subproblems

There must be base case (to stop recursion).

Conquer (solve) each subproblem recursively


Combine (merge) solutions to subproblems into a
solution to the original problem

Nontrivial strategy:
1. Split the array in half
2. Find the MAX and MIN of both halves
3. Compare the 2 MAXes and compare the 2 MINs to get
overall MAX and MIN.
TEST CASE 1

INPUT
4
2 4 1 10
OUTPUT
Minimum element is 1
Maximum element is 10
TEST CASE 2

INPUT
3
12 10 2
OUTPUT
Minimum element is 2
Maximum element is 12

#include <iostream>

using namespace std;

int main() {

int temp,n,arr[20],j,i;

cin>>n;

for(int i=0;i<n;i++)

cin>>arr[i];

for(i=1; i<n; i++)

temp=arr[i];

j=i-1;

while((temp<arr[j]) && (j>=0))

arr[j+1]=arr[j];

j=j-1;

arr[j+1]=temp;

int max,min;

min=arr[0];

max=arr[n-1];

cout<<"Minimum element is "<<min<<'\n';

cout<<"Maximum element is "<<max;


return 0;

}
Q. 23: Bishu and Soldiers
QUESTION DESCRIPTION

Bishu went to fight for Coding Club. There were N soldiers with various powers. There will be Q rounds to
fight and in each round Bishu's power will be varied. With power M, Bishu can kill all the soldiers whose
power is less than or equal to M(<=M).

After each round, All the soldiers who are dead in previous round will reborn.Such that in each round there
will be N soldiers to fight. As Bishu is weak in mathematics, help him to count the number of soldiers that he
can kill in each round and total sum of their powers.

1<=N<=10000

1<=power of each soldier<=100

1<=Q<=10000

1<=power of bishu<=100
TEST CASE 1

INPUT
4
1 2 3 4
3
3
10
2
OUTPUT
3 6
4 10
2 3
TEST CASE 2

INPUT
7
1 2 3 4 5 6 7
3
3
10
2
OUTPUT
3 6
7 28
2 3

#include<bits/stdc++.h>

using namespace std;


int ans;

void binary(int N,int arr[],int el)

int start=0,end=N-1,mid;

ans=0;

while(start<=end)

mid=(start+end)/2;

if(arr[mid]<=el)

ans=mid+1;

// break;

start=mid+1;

//break;

else if(arr[mid]>el)

end=mid-1;

int main()

int N,arr[99999],sum[99999]={0},q,el;

scanf("%d",&N);

for(int A=0;A<N;A++)

scanf("%d",&arr[A]);

sum[A+1]=sum[A]+arr[A];

}
sort(arr,arr+N);

for(int A=0;A<N;A++)

sum[A+1]=sum[A]+arr[A];

scanf("%d",&q);

while(q--)

scanf("%d",&el);

if(arr[N-1]<el) printf("%d %d\n",N,sum[N]);

else if(arr[0]>el) printf("0 0\n");

else

binary(N,arr,el);

printf("%d %d\n",ans,sum[ans]);

return 0;

}
QUESTION DESCRIPTION

A typical Divide and Conquer algorithm solves a problem using following three steps.

1. Divide: Break the given problem into subproblems of same type.


2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers

Closest Pair of Points The problem is to find the closest pair of points in a set of points in x-y plane. The
problem can be solved in O(n^2) time by calculating distances of every pair of points and comparing the
distances to find the minimum.

The Divide and Conquer algorithm solves the problem in O(nLogn) time.
TEST CASE 1

INPUT
4
10 20
5 1
2 10
3 4
OUTPUT
The smallest distance is 3.605551
TEST CASE 2

INPUT
6
2 3
12 30
40 50
5 1
12 10
3 4
OUTPUT
The smallest distance is 1.414214

#include <stdio.h>

#include <float.h>

#include <stdlib.h>

#include <math.h>

struct Point

int x, y;

};

int compareX(const void* a, const void* b)

Point *p1 = (Point *)a, *p2 = (Point *)b;

return (p1->x - p2->x);

int compareY(const void* a, const void* b)

Point *p1 = (Point *)a, *p2 = (Point *)b;

return (p1->y - p2->y);

float dist(Point p1, Point p2)

{
return sqrt( (p1.x - p2.x)*(p1.x - p2.x) +

(p1.y - p2.y)*(p1.y - p2.y)

);

float bruteForce(Point P[], int n)

float min = FLT_MAX;

for (int i = 0; i < n; ++i)

for (int j = i+1; j < n; ++j)

if (dist(P[i], P[j]) < min)

min = dist(P[i], P[j]);

return min;

float min(float x, float y)

return (x < y)? x : y;

float stripClosest(Point strip[], int size, float d)

float min = d;

qsort(strip, size, sizeof(Point), compareY);

for (int i = 0; i < size; ++i)

for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)

if (dist(strip[i],strip[j]) < min)

min = dist(strip[i], strip[j]);

return min;

float closestUtil(Point P[], int n)

{
if (n <= 3)

return bruteForce(P, n);

int mid = n/2;

Point midPoint = P[mid];

float dl = closestUtil(P, mid);

float dr = closestUtil(P + mid, n-mid);

float d = min(dl, dr);

Point strip[n];

int j = 0;

for (int i = 0; i < n; i++)

if (abs(P[i].x - midPoint.x) < d)

strip[j] = P[i], j++;

return min(d, stripClosest(strip, j, d) );

float closest(Point P[], int n)

qsort(P, n, sizeof(Point), compareX);

return closestUtil(P, n);

int main()

int i,a;

scanf("%d",&a);

Point P[a] ;

for(i=0;i<a;i++)

scanf("%d%d",&P[i].x,&P[i].y);

int n = sizeof(P) / sizeof(P[0]);

printf("The smallest distance is %f", closest(P, n));


return 0;

SESSION: Divide and Conquer


Q. 25: Shil and Lucky String
QUESTION DESCRIPTION

Shil is your new boss and he likes lucky strings very much. A string is called lucky if and only if each
character from first half of the string can be paired to each character from second half of the string. AND:

In each pair, a character from the first half is strictly greater than a character from the second half OR
In each pair, a character from the first half is strictly lesser than a character from the second half OR
In each pair, a character from the first half is equal to character from the second half.
Each character should be used exactly once in pairing.

Your are given a string S. You want to change the minimum number of characters to make this string lucky so
that you can gift it to your boss.

Note that each character in lucky string should be in lower case alphabet ( 'a' - 'z' ).

Input format:
The first line consists of an integer N. The second line consists of N lower case characters.

Output format:
Print minimum number of changes required to make given string lucky.

Constraints:
1 <= N <= 10^5
N will be an even integer.
TEST CASE 1

INPUT
6
aabbbb
OUTPUT
1
TEST CASE 2

INPUT
4
nscl
OUTPUT
0

#include<iostream>

using namespace std;


#include<bits/stdc++.h>

int has1[26],has2[26];

int main()

int n;

cin>>n;

char ff[n+10],ss[n+10];

for(int i=0;i<n/2;i++)

cin>>ff[i];

has1[ff[i]-'a']++;

for(int i=0;i<n/2;i++)

cin>>ss[i];

has2[ss[i]-'a']++;

sort(ff,ff+n/2);

sort(ss,ss+n/2);

//case 1

int ans1=0,ans2=0,ans3=0;

for(int i=0;i<26;i++)

ans1+=abs(has1[i]-has2[i]);

// cout<<"i " <<i<<" " <<has1[i]<<" " <<has2[i]<<endl;

int i=0,j=0;
while(i!=n/2 && j!=n/2)

if(ff[i]<ss[j])

i++;

j++;

else

j++;

ans2=abs(j-i);

i=0,j=0;

while(i!=n/2 && j!=n/2)

if(ss[i]<ff[j])

i++;

j++;

else

j++;

}
ans3=abs(j-i);

// cout<<ans1<<" "<<ans2<<" "<<ans3<<endl;

cout<<min(min(ans1/2,ans2),ans3);

return 0;

SESSION: Divide and Conquer


Q. 26: Charsi in Love
QUESTION DESCRIPTION

Its been a few days since Charsi is acting weird. And finally you(his best friend) came to know that its because
his proposal has been rejected.

He is trying hard to solve this problem but because of the rejection thing he can't really focus. Can you help
him? The question is: Given a number n , find if n can be represented as the sum of 2 desperate numbers (not
necessarily different) , where desperate numbers are those which can be written in the form of (a*(a+1))/2
where a > 0 .

Input :

The first input line contains an integer n (1<=n<=10^9).

Output :

Print "YES" (without the quotes), if n can be represented as a sum of two desperate numbers, otherwise print
"NO" (without the quotes).
TEST CASE 1

INPUT
45
OUTPUT
NO
TEST CASE 2

INPUT
256
OUTPUT
YES

#include <stdio.h>

#include<math.h>

int binarySearch(int low,int high,int key)

while(low<=high)
{

int mid=(low+high)/2;

int x = (mid*(mid+1));

if(x<key)

low=mid+1;

else if(x>key)

high=mid-1;

else

return mid;

return -1;

int main()

int n,i,b;

int flag=0;

scanf("%d",&n);

for(i=1;i<=sqrt(n);i++){

b = n - ((i*(i+1))/2);

int y = binarySearch(1,sqrt(2*b),2*b);

if(y>0) {

flag =1;
break;

if(flag==1)

printf("YES");

else

printf("NO");

return 0;

Q. 27: Sort me this way !


QUESTION DESCRIPTION

Given an array A consisting of integers of size N, you need to sort this array in non-decreasing order on the
basis of the absolute value of the integers in the array. Print the sorted array to output then.

Input:

The first line consists of a single integer N, the number of elements in the array. The next line consists of N
space separated elements. No two elements in the array will have same absolute value.

Output:

You need to print the absolute sorted array. See the sample output for clarification.

Constraints:

1<=N<=10^5

-10^9<= A[i] <= 10^9 A[i] is the ith element of the array.
TEST CASE 1

INPUT
8
5 6 1 2 8 9 3 4
OUTPUT
1 2 3 4 5 6 8 9
TEST CASE 2

INPUT
10
9 -10 -11 20 1 2 -3 4 -5 6
OUTPUT
-11 -10 -5 -3 1 2 4 6 9 20
#include <iostream>

using namespace std;

int main() {

int n,i,j,temp;

cin>>n;

int a[50];

for(i=0;i<n;i++)

cin>>a[i];

for(i=1; i<n; i++)

temp=a[i];

j=i-1;

while((temp<a[j]) && (j>=0))

a[j+1]=a[j];

j=j-1;

a[j+1]=temp;

for(i=0;i<n;i++)

cout<<a[i]<<" ";

}
return 0;

Q. 28: Monk and Modulo Based Sorting


QUESTION DESCRIPTION

Monk likes to experiment with algorithms. His one such experiment is using modulo in sorting.He describes an
array modulo sorted as:

Given an integer k, we need to sort the values in the array according to their modulo with k. That is, if there are
two integers a and
b, and a%k<b%k, then a would come before b in the sorted array. If a%k=b%k , then the integer which comes
first in the given array remains first in the sorted array.

Given an initial array, you need to print modulo sorted array.

Input:
The first line consists of two integers N and k, N being the number of elements in the array and k is the number
with which we need to take the modulo.
The next line consists of N space separated integers , denoting the elements of the array A.

Output:
Print the modulo sorted array of the given array.

Constraints:

1<=N<=10^4
1<=k<=10^9
1<=A[i]<=10^9
1<=i<=N
TEST CASE 1

INPUT
5 6
12 18 17 65 46
OUTPUT
12 18 46 17 65
TEST CASE 2

INPUT
4 6
4 6 2 8
OUTPUT
6 2 8 4

#include <iostream>

using namespace std;


int main(){

int n,key,c,idx,k,key2;

cin >> n;

cin>>k;

int arr[n];

for (int i=0; i<n; i++){

cin >> arr[i];

for (int i=1;i<n;i++){

key = arr[i]%k;

key2 = arr[i];

c = i-1;

idx = i;

while (c>=0){

if (key<arr[c]%k){

arr[idx] = arr[c];

arr[c] = key2;

idx-=1;

else{

break;

c-=1;

for (int i=0;i<n;i++){

cout << arr[i] << " ";

return 0;
}

SESSION: Divide and Conquer


Q. 29: Missing Soldiers
QUESTION DESCRIPTION

An infinite army of ants is marching on an infinite 2-D plane. Since ants are disciplined, here's how they
march: each ant chooses exactly one x coordinate and moves along it in positive y direction, starting from (x,
0). There exists exactly one ant for each x coordinate on that plane and hence there are infinite ants!

There are N horizontal barriers lying on this plane. The ith barrier is defined by (xi, yi) and di, which means
that the barrier is blocking all ants which want to pass through points lying on line segment connecting (xi, yi)
and (xi + di, yi). Once an ant encounters a barrier, it stops moving.

Given all the barriers, your task is to find the total number of ants, that will be ever blocked at some point in
their march.

INPUT

The first line contains an integer N which denotes the number of barriers. Next N lines follow, each contains 3
space separated integers, "xi yi di" as explained in problem statement above.

Note: The barriers in the input may overlap.

OUTPUT

Output a single integer, the number of ants that will be ever blocked at some point in their march.

CONSTRAINTS

1<= N <= 10^5


1 <= xi, yi, di <= 10^9
TEST CASE 1

INPUT
2
1 1 4
7 3 5
OUTPUT
11
TEST CASE 2

INPUT
6
6 9 5
8 10 8
3 6 4
8 3 6
3 3 8
4 2 4
OUTPUT
14
#include <iostream>

#include <cstdio>

#include <string>

#include <sstream>

#include <vector>

#include <set>

#include <map>

#include <queue>

#include <stack>

#include <cmath>

#include <algorithm>

#include <cstring>

#include <ctime>

#include <cassert>

using namespace std;

#define pb push_back

#define mp make_pair

#define pii pair<int,int>

#define vi vector<int>

#define SZ(x) ((int)(x.size()))

#define fi first

#define se second

#define FOR(i,n) for(int (i)=0;(i)<(n);++(i))

#define FORI(i,n) for(int (i)=1;(i)<=(n);++(i))

#define IN(x,y) ((y).find((x))!=(y).end())

#define ALL(t) t.begin(),t.end()

#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)

#define REP(i,a,b) for(int (i)=(a);(i)<=(b);++i)


#define REPD(i,a,b) for(int (i)=(a); (i)>=(b);--i)

#define REMAX(a,b) (a)=max((a),(b));

#define REMIN(a,b) (a)=min((a),(b));

#define DBG cerr << "debug here" << endl;

#define DBGV(vari) cerr << #vari<< " = "<< (vari) <<endl;

typedef long long ll;

const int MINN = 1;

const int MAXN = 1e5;

const int MINV = 1;

const int MAXV = 1e9;

pii v[MAXN];

int main()

ios_base::sync_with_stdio(0);

int n;

cin >> n;

assert(n >= MINN && n <= MAXN);

FOR(i, n)

int x, y, d;

cin >> x >> y >> d;

assert(x >= MINV && x <= MAXV);

assert(y >= MINV && y <= MAXV);

assert(d >= MINV && d <= MAXV);

v[i] = mp(x, x + d);

sort(v, v + n);

int res = 0;

int cur = 1;
//INVARIANT: cur is the first not already covered point

FOR(i, n)

cur = max(cur, v[i].fi);

if(v[i].se >= cur)

res += v[i].se - cur + 1;

cur = v[i].se + 1;

cout << res << endl;

return 0;

}
Q. 30: Strassen Algorithm
QUESTION DESCRIPTION

Write a program to compute product of two matrices using Strassen Multiplication algorithm. Here the
dimensions of matrices must be a power of 2.

Input Format:
Order of the matrix
Enter the elements of matrix 1
Enter the elements of matrix 2
TEST CASE 1

INPUT
2
1 2
3 4
5 6
7 8
OUTPUT
19 22
43 50
TEST CASE 2

INPUT
2
4 2
1 4
2 6
1 4
OUTPUT
10 32
6 22

#include <stdio.h>

int num;

void strassen(int a[][num], int b[][num], int c[][num], int size) {

int p1[size/2][size/2], p2[size/2][size/2], p3[size/2][size/2], p4[size/2][size/2], p5[size/2][size/2],


p6[size/2][size/2], p7[size/2][size/2];

int temp1[size/2][size/2], temp2[size/2][size/2];

int i, j;

if(size >= 2) {

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i][j] + a[i + size / 2][j + size / 2];

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i][j] + b[i + size / 2][j + size / 2];

num = size / 2;

strassen(temp1, temp2, p1, size / 2);

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i + size / 2][j] + a[i + size / 2][j + size / 2];

for(i = 0; i < size / 2; i++) {


for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i][j];

num = size / 2;

strassen(temp1, temp2, p2, size / 2);

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i][j];

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i][j + size / 2] - b[i + size / 2][j + size / 2];

num = size / 2;

strassen(temp1, temp2, p3, size / 2);

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i + size / 2][j + size / 2];

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i + size / 2][j] - b[i][j];

}}

num = size / 2;

strassen(temp1, temp2, p4, size / 2);


for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i][j] + a[i][j + size / 2];}

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i + size / 2][j + size / 2];

}}

num = size / 2;

strassen(temp1, temp2, p5, size / 2);

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i + size / 2][j] - a[i][j];

}}num = size / 2;

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i][j] + b[i][j + size / 2];

}}num = size / 2;

strassen(temp1, temp2, p6, size / 2);

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

temp1[i][j] = a[i][j + size / 2] - a[i + size / 2][j + size / 2];

}}

for(i = 0; i < size / 2; i++)

{for(j = 0; j < size / 2; j++) {

temp2[i][j] = b[i + size / 2][j] + b[i + size / 2][j + size / 2];

}}

num = size / 2;

strassen(temp1, temp2, p7, size / 2);


for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

c[i][j] = p1[i][j] + p4[i][j] - p5[i][j] + p7[i][j];

}}

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

c[i][j + size / 2] = p3[i][j] + p5[i][j];

}}

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

c[i + size / 2][j] = p2[i][j] + p4[i][j];}}

for(i = 0; i < size / 2; i++) {

for(j = 0; j < size / 2; j++) {

c[i + size / 2][j + size / 2] = p1[i][j] + p3[i][j] - p2[i][j] + p6[i][j];}}

}else if(size == 1) {

c[0][0] = a[0][0] * b[0][0];

}}

int padding(int num) {

int original_num = num, lower_power = 0, i, actual_num = 1;

if(num == 1)

return 1;

while(num > 1) {

lower_power++;

num /= 2;

}for(i = 0; i < lower_power; i++) {

actual_num *= 2;}
if(actual_num == original_num)

return original_num;

else

return actual_num * 2;}

int main() {

int i, j, temp;

scanf("%d", &num);

temp = num;

if(num <= 0)

return 0;

num = padding(num);

int a[num][num], b[num][num], c[num][num];

for(i = 0; i < temp; i++) {

for(j = 0; j < temp; j++) {

scanf("%d", &a[i][j]);

for(j = temp; j < num; j++) {

a[i][j] = 0;

for(i = temp; i < num; i++)

for(j = 0; j < num; j++)

a[i][j] = 0;

for(i = 0; i < temp; i++) {

for(j = 0; j < temp; j++) {

scanf("%d", &b[i][j]);

}
for(j = temp; j < num; j++) {

b[i][j] = 0;

for(i = temp; i < num; i++)

for(j = 0; j < num; j++)

b[i][j] = 0;

strassen(a, b, c, num);

for(i = 0; i < temp; i++) {

for(j = 0; j < temp; j++) {

printf("%d ", c[i][j]);

printf("\n");

return 0;}

Q. 32: EASY STRONG PERMUTATION


QUESTION DESCRIPTION

Kevin has a sequence of integers a1, a2, ..., an. Define the strength of the sequence to be

|a1 - a2| + |a2 - a3| + ... + |an-1 - an| + |an - a1|.

Kevin wants to make his sequence stronger, so he reorders his sequence into a new sequence b1, b2, ..., bn. He
wants this new sequence to be as strong as possible. What is the largest possible strength of the resulting
sequence?

Input

The input consists of 2 lines. The first line has a positive integer n. The second line contains the n integers a1,
a2, ..., an.

Output

Output a single integer: the maximum possible strength.

Constraints
1 <= n <= 10^5.
|ai| <= 10^9.

Note that ai can be negative.


TEST CASE 1

INPUT
4
1 2 4 8
OUTPUT
18
TEST CASE 2

INPUT
5
1 2 4 8 10
OUTPUT
30

#include <iostream>

#include<math.h>

using namespace std;

int main() {

int n;

cin>>n;

int a[n];

for(int i=0;i<n;i++)

cin>>a[i];

int s=0,i,j;

for( i=0,j=n-1;j>=0;i++,j--)

int t=a[i]-a[j];

if(t<0)

t=-t;

s=s+t;

}
cout<<s;

return 0;

}
Q. 33: GREEDY FLORIST
QUESTION DESCRIPTION

You and K-1 friends want to buy N flowers. Each flower fi has some cost ci. The florist is greedy and wants to
maximize his number of new customers, so he increases the sale price of flowers for repeat customers; more
precisely, if a customer has already purchased x flowers, price P for fi is Pfi=(x+1) * ci .

Find and print the minimum cost for your group to purchase N flowers.

Note: You can purchase the flowers in any order.

Input Format:

The first line contains two integers, N(number of flowers to purchase) and K(the size of your group of friends,
including you).
The second line contains N space-separated positive integers describing the cost (c0, c1,...., cN-2, CN-1) for
each flower fi.

Constraints
1 <= N, K <=100
1 <= ci <= 10^6
answer < 2^31
0 <= i <= N-1
Output Format

Print the minimum cost for buying N flowers.


TEST CASE 1

INPUT
3 3
2 5 6
OUTPUT
13
TEST CASE 2

INPUT
3 2
2 5 6
OUTPUT
15

#include <iostream>

#include<vector>

#include<algorithm>
using namespace std;

int main()

int n,k;

cin>>n>>k;

vector<int>C(n),t(k);

for(int i=0;i<n;i++)

cin>>C[i];

for(int i=0;i<k;i++)

t[i]=0;

int res=0,j=0;

sort(C.begin(),C.end());

for(int i=n-1;i>=0;i--)

res+=(t[j]+1)*C[i];

t[j]++;

j=(j+1)%k;

}cout<<res<<" ";

return 0;

Q. 35: SHARPEN THE PENCILS


QUESTION DESCRIPTION

Madhav and Riya were getting bored. So they decided to play a game.

They placed N pencils in a line. Madhav starts to sharpen pencil from left to right, and Riya from right to left.
For each pencil, its length is known.
Madhav sharpens with speed twice that of Riya. If a player starts to sharpen the pencil, other player can't touch
it. If both players reach the same pencil simultaneously, Madhav gets to sharpen pencil as he snatches it away
from Riya.

How many pencils each of the players will sharpen?


Input

The first line contains one integer T, the number of test cases.
The first line of each test case contains one integer N,the number of pencils.
The second line contains a sequence , A1, A2, A3 . . . An where Ai denotes length of ith pencil.

Output
Print two numbers X and Y separated by space, where X is the number of pencils sharpened by Madhav, and Y
is the number of pencils sharpened by Riya.

Constraints
1 <= T <= 100
1 <= N <= 100000
1<= Ai <= 10^7
TEST CASE 1

INPUT
1
5
2 9 8 2 7
OUTPUT
3 2
TEST CASE 2

INPUT
2
5
2 9 8 2 7
4
1 9 3 2
OUTPUT
3 2
2 2

#include <stdio.h>

int scan_f()

int cc = getc(stdin);

for (;cc < '0' || cc > '9';)

cc = getc(stdin);

int ret = 0;

for (;cc >= '0' && cc <= '9';)

{
ret = ret * 10 + cc - '0';

cc = getc(stdin);

return ret;

int main()

int t;

scanf("%d",&t);

while(t--)

int n,i;

scanf("%d",&n);

int x,y=0,a[n],sum=0,h=0;

for(i=0;i<n;i++)

a[i]=scan_f();

sum+=a[i];

x=sum;

y=0;

int y1;

for(i=n-1;i>=0;i--)

x-=a[i];

y+=a[i];

if(x>2*y)

h++;
}

else

if(x>2*y1)

h++;

break;

y1=y;

printf("%d %d\n",n-h,h);

return 0;

Q. 36: SHERLOCK AND THE BEAST


QUESTION DESCRIPTION

Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical.
Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their
supercomputer, The Beast.

Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The
Beast with a virus; however, he also gives him a clue a number, N. Sherlock determines the key to removing
the virus is to find the largest Decent Number having N digits.

A Decent Number has the following properties:

1. Its digits can only be 3's and/or 5's.


2. The number of 3's it contains is divisible by 5.
3. The number of 5's it contains is divisible by 3.
4. If there are more than one such number, we pick the largest one.
Constraints:
1 <= T <= 20
1 <=N <= 100000

Input Format:

The first line is an integer, T , denoting the number of test cases.

The T subsequent lines each contain an integer, N, detailing the number of digits in the number.
Output Format

Print the largest Decent Number having N digits; if no such number exists, tell Sherlock by printing -1.

Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your
task is to help Sherlock find the key before The Beast is destroyed!
TEST CASE 1

INPUT
4
1
3
5
11
OUTPUT
-1
555
33333
55555533333
TEST CASE 2

INPUT
3
5
7
11
OUTPUT
33333
-1
55555533

#include <stdio.h>

int main()

int i,numThrees,a0,t,n;

scanf("%d",&t);

for(a0 = 0; a0 < t; a0++)

scanf("%d", &n);

numThrees = 0;

while(n%3 != 0)

{
n -= 5;

numThrees++;

if(n < 0)

printf("-1\n");

else

while(n != 0)

printf("555");

n -= 3;

for(i = 0; i < numThrees; i++)

printf("33333");

printf("\n");

return 0;

}
Q. 37: PERMUTATION OF FIRST N NATURAL NUMBERS
QUESTION DESCRIPTION

You are given an array of N integers which is a permutation of the first N natural numbers. You can swap any
two elements of the array. You can make at most K swaps. What is the largest permutation, in numerical order,
you can make?

Input Format:

The first line of the input contains two integers, N and K, the size of the input array and the maximum swaps
you can make, respectively. The second line of the input contains a permutation of the first N natural numbers.

Output Format:

Print the lexicographically largest permutation you can make with at most K swaps.

Constraints
1 <= N <= 10^5
1 <= K <= 10^9
TEST CASE 1

INPUT
5 1
4 2 3 5 1
OUTPUT
5 2 3 4 1
TEST CASE 2

INPUT
3 1
2 1 3
OUTPUT
3 1 2

#include<bits/stdc++.h>

using namespace std;

void KswapPermutation(int arr[], int n, int k)

int pos[n+1];

for (int i = 0; i < n; ++i)

pos[arr[i]] = i;

for (int i=0; i<n && k; ++i)

if (arr[i] == n-i)

continue;

int temp = pos[n-i];

pos[arr[i]] = pos[n-i];

pos[n-i] = i;

swap(arr[temp], arr[i]);

--k;
}

int main()

int arr[10],k,n,i;

cin>>n;

cin>>k;

for(i=0;i<n;i++)

cin>>arr[i];

KswapPermutation(arr, n, k);

//cout << k << " swaps:n";

for (int i=0; i<n; ++i)

printf("%d ", arr[i]);

return 0;

}
Q. 38: JUMPING CHAMPA
QUESTION DESCRIPTION

Champa loved traveling the world. He loved going from one city to the other. Being the miser that he is, he
never wishes spend any money. Champa, instead, jumps from one city to the other. Also he likes trips of high
quality.

He can start at any city of his choice. Given that he has visited the ith city, he will not visit it again, he will
only visit the remaining unvisited cities. This means that Champa will jump n - 1 times in total, so that he can
visit all of the n cities.

Given two cities at heights, A and B, the amount of money spent is Q * |A - B| where Q is the quality of a trip.
Champa has a list of cities he's dying to visit. Can you tell the minimum amount of money Champa would
have to spend to visit all of the cities?

Input

The first line contains T, the number of test cases.


Each test case is described by two lines.

The first line of each test case contains N describing the number of cities that Champa wishes to visit, followed
by Q, which is the quality of the whole trip.
The following line contains N space separated integers Hi which describes the height of the ith city.

Output
T lines each containing a single integer such that the answer to the ith line contains the answer to the ith test
case.

Constraints

1 <= T, Q, N <= 10^3


1 <= Hi <= 3 * 10^6
TEST CASE 1

INPUT
2
2 4
2 1
1 5
3
OUTPUT
4
0
TEST CASE 2

INPUT
2
1 5
3
2 4
2 1
OUTPUT
0
4

#include <bits/stdc++.h>

using namespace std;

const long long maxh = 3e6 + 5;

const long long minh = -1;

int main()

int t;

cin >> t;

while (t--)

{
long long q, val, mn = maxh, mx = minh;

int n;

cin >> n >> q;

for (int i = 0; i < n; i++)

cin >> val;

mn = min(mn, val);

mx = max(mx, val);

long long ans = q * (mx - mn);

cout << ans << '\n';

return 0;

Q. 39: MAXIMUM PERIMETER TRIANGLE


QUESTION DESCRIPTION

Given n sticks of lengths l0,l1,.,ln-1, use 3 of the sticks to construct a non-degenerate triangle with the
maximum possible perimeter. Then print the lengths of its sides as 3 space-separated integers in non-
decreasing order.

If there are several valid triangles having the maximum perimeter:

1. Choose the one with the longest maximum side (i.e., the largest value for the longest side of any valid
triangle having the maximum perimeter).
2. If more than one such triangle meets the first criterion, choose the one with the longest minimum side (i.e.,
the largest value for the shortest side of any valid triangle having the maximum perimeter).
3. If more than one such triangle meets the second criterion, print any one of the qualifying triangles.

If no non-degenerate triangle exists, print -1.

Input Format

The first line contains single integer, n, denoting the number of sticks.

The second line contains n space-separated integers, l0,l1,.,ln-1, describing the respective stick lengths.

Constraints
3 <= n <= 50
1 <= li <= 10^9

Output Format

Print 3 non-decreasing space-separated integers, a ,b , and c (where a <= b <= c) describing the respective
lengths of a triangle meeting the criteria in the above Problem Statement.
If no non-degenerate triangle can be constructed, print -1.
TEST CASE 1

INPUT
5
1 1 1 3 3
OUTPUT
1 3 3
TEST CASE 2

INPUT
3
1 2 3
OUTPUT
-1

#include <bits/stdc++.h>

using namespace std;

#define sz(x) ((int) (x).(size())

#define forn(i,n) for (int i=0;i<int(n);i++)

typedef long long ll;

typedef long long i64;

const int inf=int(1e9)+int(1e5);

const ll infl =ll(2e18)+ll(1e10);

const int maxn=100100;

int n;

int a[maxn];

int main()

#ifdef LOCAL

assert(freopen("test.in","r",stdin));
#endif

cin>>n;

forn(i,n)

cin>>a[i];

sort(a,a+n);

reverse(a,a+n);

forn(i,n-2)

if(a[i+2]+a[i+1]<=a[i])

continue;

cout<<a[i+2]<<' '<<a[i+1]<<' '<<a[i]<<'\n';

return 0;

cout<<-1<<'\n';

}
Q. 40: CHANDU & CONSECUTIVE LETTERS
QUESTION DESCRIPTION

Chandu is very fond of strings. (Or so he thinks!) But, he does not like strings which have same consecutive
letters. No one has any idea why it is so. He calls these strings as Bad strings. So, Good strings are the strings
which do not have same consecutive letters.

Now, the problem is quite simple. Given a string S, you need to convert it into a Good String.

You simply need to perform one operation - if there are two same consecutive letters, delete one of them.

Input:
The first line contains an integer T, denoting the number of test cases.
Each test case consists of a string S, which consists of only lower case letters.

Output:
For each test case, print the answer to the given problem.

Constraints:
1 <= T <= 10
1 <= |S| <= 30
TEST CASE 1

INPUT
3
abb
aaab
ababa
OUTPUT
ab
ab
ababa
TEST CASE 2

INPUT
2
ab
abc
abcd
OUTPUT
ab
abc

#include <iostream>

#include <vector>

using namespace std;

int main(void)

int cases;

cin>>cases;

while(cases--)

string arr;cin>>arr;

char flag=arr[0];

cout<<flag;

int a=arr.length();

for(int i=1;i<a;i++)

if(arr[i]!=flag)

cout<<arr[i];
flag=arr[i];

cout<<endl;

Q. 41: LET'S BEGIN!


QUESTION DESCRIPTION

February Easy Challenge 2015 is underway. Hackerearth welcomes you all and hope that all you awesome
coders have a great time. So without wasting much of the time let's begin the contest.

Prime Numbers have always been one of the favourite topics for problem setters.

Aishwarya is a mathematics student at the Department of Mathematics and Computing, California. Her teacher
recently gave her an intriguing assignment with only a single question. The question was to find out the
minimum number of single digit prime numbers which when summed equals a given number X.

Input:
The first line contains T denoting the number of test cases. Each of the next T lines contains a single integer X.

Output:
Print the minimum number required. If it is not possible to obtain X using single digit prime numbers, output -
1.

Constraints:
1<=T<=100
1<=X<=10^6
TEST CASE 1

INPUT
4
7
10
14
11
OUTPUT
1
2
2
3
TEST CASE 2

INPUT
3
5688
11126
17529
OUTPUT
814
1590
2505

#include <cstdio>

#include <cassert>

#include <algorithm>

#include <cstdlib>

using namespace std;

#define MAXT 100

#define MAXN 1000000

#define INF 1000000000

int dp[MAXN+5];

int pr[] = {2, 3, 5, 7};

int len = 4;

void solve(){

for(int i=0;i<=MAXN;i++)

dp[i]=INF;

dp[2] = 1;

dp[3] = 1;

dp[5] = 1;

dp[7] = 1;

for(int i=1;i<=MAXN;i++){

for(int j=0; j<len;j++){

if(i-pr[j]>=0)

dp[i] = min(dp[i], dp[i-pr[j]] + 1);

for(int i=0;i<=MAXN;i++)
if(dp[i]>=INF)

dp[i] = -1;

return;

int main(){

solve();

int N, T;

scanf("%d", &T);

assert(T>0);

assert(T<=MAXT);

while(T--){

scanf("%d", &N);

assert(N>0);

assert(N<=MAXN);

printf("%d\n", dp[N]);

return 0;

}
Q. 42: PRIME NUMBERS AGAIN
QUESTION DESCRIPTION

Panda can do any problem anytime and anywhere. Panda is doing an extensive research on prime numbers.
Milinda has got a question for Panda. The only way for Panda to impress Milinda is by solving this question.

Given a number N, find the minimum number of primatic numbers which sum upto N.

A primatic number refers to a number which is either a prime number or can be expressed as power of prime
number to itself i.e. prime^prime e.g. 4, 27, etc.

Note: 8, 32, etc are not primatic numbers.


Panda is very sad since he is unable to solve the problem. Please help Panda in solving this problem.

Input Format:
The first line will contain two integers: T, the number of test cases.
Each test case consists of a single integer N.

Output Format:
For each query output the minimum number of primatic numbers which can sum upto N.
Constraints:
1 <= T <= 10^5
2 <= N <= 10^4

Subtask 1:
T = 100, 2 <= N <= 1000 - 20 points

Subtask 2:
T = 10^5, 2 <= N <= 104 - 80 points
TEST CASE 1

INPUT
2
6 3
OUTPUT
2
1
TEST CASE 2

INPUT
11
4 2 1 3 5 7 6 9 8 10 21
OUTPUT
1
1
0
1
1
1
2
2
2
2
2

#include<cstdio>

#include<iostream>

#include<cstdlib>

#include<cmath>

#include<cstring>

#include<algorithm>

#include<climits>

#include<vector>

#include<stdio.h>
#include<cassert>

using namespace std;

#define FOR(i,a,b) for(i= a ; i < b ; ++i)

#define rep(i,n) FOR(i,0,n)

#define INF INT_MAX

#define ALL(x) x.begin(),x.end()

#define pb push_back

#define sz(x) int(x.size())

#define min(a,b) ((a)<(b)?(a):(b))

#define si(n) scanf("%d",&n)

#define pi(n) printf("%d ",n)

#define pin(n) printf("%d\n",n)

#define pln(n) printf("%lld\n",n)

#define pl(n) printf("%lld ",n)

#define sl(n) scanf("%lld",&n)

#define ll long long int

#define mod (int)(1e9 + 7)

#define MAX 10000

ll modpow(ll a,ll n,ll temp){ll res=1,y=a;while(n>0){if(n&1)res=(res*y)%temp;y=(y*y)%temp;n/=2;}return


res%temp;}

int isprimeat[MAX+20], dp[MAX+20];

vector<int> primeat;

//Finding all prime numbers till 10000

void seive()

ll i,j;

isprimeat[0]=1;

isprimeat[1]=1;

for(i=2;i<=MAX;i++)
{

if(isprimeat[i]==0)

for(j=i*i;j<=MAX;j+=i)

isprimeat[j]=1;

for(i=2;i<=MAX;i++)

if(isprimeat[i]==0)

primeat.pb(i);

isprimeat[4]=isprimeat[27]=isprimeat[3125]=0;

primeat.pb(4);

primeat.pb(27);

primeat.pb(3125);

int main()

int i,t,n,sz,j;

seive();

sort(primeat.begin(), primeat.end());

dp[2]=1;

dp[3]=1;

sz=primeat.size();
//Pre-computing the required query using DP

FOR(i,4,MAX+1)

dp[i]=mod;

if(isprimeat[i]==0)

dp[i]=1;

continue;

rep(j,sz)

if(i-primeat[j]<2)

break;

dp[i]=min(dp[i], dp[i-primeat[j]]+1);

//Checking the value of dp[n] array according to GoldBach conjecture

FOR(i,2,MAX+1)

if(isprimeat[i]==0)

assert(dp[i]==1);

else if(i%2==0)

assert(dp[i]==2);

else

assert(dp[i]<=3);

si(t);
assert(t>=1 && t<=100000);

while(t--)

si(n);

pin(dp[n]);

return 0;

}
Q. 44: SUPER TWO LETTER STRINGS
QUESTION DESCRIPTION

Two letter strings are the strings consisting of only two letters "X" and "Y". A string is "super two letter string"
if

a) It does not have leading "X" letters.


b) It does not contain P consecutive "X" letters.
Your task is to find total number of Super two letter strings of length N.

Input :

The first line contains the number of test cases T . Each test case consists of two space separated integers - N
and P .

Output :

For each test case output total number of Super two letter strings of length N modulo 1000000007(10^9+7).

Constraints :

1 <= T <= 100


1 <= N <= 10^4
1 <= P <= 10
TEST CASE 1

INPUT
2
2 1
4 2
OUTPUT
1
5
TEST CASE 2

INPUT
7
2 3
1 4
5 1
6 3
1 3
4 2
7 2
OUTPUT
2
1
1
24
1
5
21

#include<stdio.h>

#include<string.h>

#define mod 1000000007

int main()

long long int dp[10005];

int n,t,k,i,j;

scanf("%d",&t);

while(t--)

memset(dp,0,sizeof(dp));

scanf("%d%d",&n,&k);

dp[0]=1;

for(i=1;i<=n;i++)

for(j=i-1;(j>=0)&&(i-j<=k);j--)

dp[i]+=dp[j];
dp[i]=(dp[i])%mod;

printf("%lld\n",dp[n]);

return 0;

Q. 45: Little Deepu and his Girlfriend


QUESTION DESCRIPTION

Little Deepu recently got a new job, so to celebrate, he decided to take his girfriend, Kate, out on a fancy
candle light dinner.
To make things perfect for Kate, Deepu planned the night to the last detail. The food, the music, the ambience,
everything was perfect, but stupidly enough Deepu forgot to get her a present.

After dinner, Kate asks our Deepu for her gift, when she finds out that he hasn't got her any she gets upset, to
try smooth things with her, he proposes a game, this makes Kate so angry that she dumps him right there(bad
move Deepu). Well its safe to say the rest of the evening was uneventful for Little Deepu but the game he
proposed was pretty interesting.

To put the game a bit formally, we have two players Little Deepu and Kate and M items in the bag B, also we
have a game set S with N elements, each element of game set is an integer.

The game is played as follows, each player takes turn to pick an element from the game set S and removes that
number of items from the bag, the player that is unable to remove the items from the bag looses the game.
Little Deepu start the game ,If both Little Deepu and Kate play the game optimally, your task is to determine
who wins the game.

Input:
First line contains a integer T , number of test cases. Each test case contain two lines , first line contain two
integer M and N and second line contain elements of S.

Output:
For each test case print name of the winner of the game .

Constraints:
1<=T <= 1000
1 <= M <= 10000
1 <= N <= 100
1 <= S[i] <= M
TEST CASE 1

INPUT
2
3 2
1 2
5 3
1 2 3
OUTPUT
Kate
Little Deepu
TEST CASE 2

INPUT
3
3 3
2 1 4
4 2
1 2
4 3
2 6 1
OUTPUT
Kate
Little Deepu
Little Deepu
#include <iostream>

using namespace std;

int a[100001];

int b[100001];

int main()

int t,n,m,i,j,k;

scanf("%d",&t);

while(t--){

scanf("%d%d",&m,&n);

for(i=0;i<=m;i++){

b[i] = 0;

for(i=0;i<n;i++){
scanf("%d",&a[i]);

for(i=0;i<=m;i++){

if(b[i]==0){

for(j=0;j<n;j++){

k =i+a[j];

if(k<=m) b[k] =1;

if(b[m])

printf("Little Deepu\n");

else

printf("Kate\n");

return 0;

}
Q. 46: Stack of Bricks
QUESTION DESCRIPTION

You and your friend decide to play a game using a stack consisting of N bricks. In this game, you can
alternatively remove 1, 2 or 3 bricks from the top, and the numbers etched on the removed bricks are added to
your score.

You have to play so that you obtain the maximum possible score. It is given that your friend will also play
optimally and you make the first move.

Input Format

First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test
case: first line will contain a number N i.e. number of elements in the stack and next line will contain N
numbers i.e. numbers etched on bricks from top to bottom.

Constraints
1 <= T <= 5
1 <= N <= 10^5
0 <= each number on brick <= 10^9

Output Format

For each test case, print a single line containing your maximum score.

TEST CASE 1

INPUT
2
5
999 1 1 1 0
5
0 1 1 1 999
OUTPUT
1001
999
TEST CASE 2

INPUT
2
5
999 0 1 1 1
5
1 1 1 0 999
OUTPUT
1000
1000

#include <cmath>

#include <cstdio>

#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

int main() {

int T;

cin>>T;

while(T > 0) {

int N;
cin>>N;

long long *bricks = new long long[N];

long long *sum = new long long[N];

for(int i = 0; i < N; i++) {

cin>>bricks[N-i-1];

sum[0] = bricks[0];

for(int i = 1; i < N; i++) {

sum[i] = sum[i-1] + bricks[i];

if(N < 4) {

cout<<sum[N-1]<<"\n";

T--;

} else {

long long *dp = new long long[N];

dp[0] = sum[0];

dp[1] = sum[1];

dp[2] = sum[2];

for(int i = 3; i < N; i++)

dp[i] = sum[i] - dp[i-3];

dp[i] = max(dp[i], sum[i] - dp[i-2]);

dp[i] = max(dp[i], sum[i] - dp[i-1]);

cout<<dp[N-1]<<"\n";

T--;

return 0;
}

Q. 47: PALINDROME COUNT


QUESTION DESCRIPTION

Given a string S, count the number of non empty sub strings that are palindromes. A sub string is any
continuous sequence of characters in the string. A string is said to be palindrome, if the reverse of the string is
same as itself.

Two sub strings are different if they occur at different positions in S

Input
Input contains only a single line that contains string S.

Output
Print a single number, the number of sub strings that are palindromes.

Constraints
1 <= |S| <= 50
S contains only lower case latin letters, that is characters a to z.
TEST CASE 1

INPUT
dskjkd
OUTPUT
7
TEST CASE 2

INPUT
fzxldqljeiiah
OUTPUT
14

#include <bits/stdc++.h>

using namespace std;

int count(char str[],int n)

int dp[n][n];

memset(dp,0,sizeof(dp));

bool P[n][n];

memset(P,false,sizeof(P));

for(int i=0;i<n;i++)

P[i][i]=true;
for(int i=0;i<n-1;i++)

if(str[i]==str[i+1])

P[i][i+1]=true;

dp[i][i+1]=1;

for(int gap=2;gap<n;gap++)

for(int i=0;i<n-gap;i++)

int j=gap+i;

if(str[i]==str[j]&&P[i+1][j-1])

P[i][j]=true;

if(P[i][j]==true)

dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1];

else

dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];

return dp[0][n-1];

int main()

char str[50];

cin>>str;

cout<<count(str,strlen(str))+strlen(str);

return 0;

}
Q. 48: Puzzle
QUESTION DESCRIPTION

Red John has committed another murder. But this time, he doesn't leave a red smiley behind. What he leaves
behind is a puzzle for Patrick Jane to solve. He also texts Teresa Lisbon that if Patrick is successful, he will
turn himself in. The puzzle begins as follows.

There is a wall of size 4xN in the victim's house. The victim also has an infinite supply of bricks of size 4x1
and 1x4 in her house. There is a hidden safe which can only be opened by a particular configuration of bricks
in the wall. In every configuration, the wall has to be completely covered using the bricks.

There is a phone number written on a note in the safe which is of utmost importance in the murder case. Gale
Bertram wants to know the total number of ways in which the bricks can be arranged on the wall so that a new
configuration arises every time.

He calls it M. Since Red John is back after a long time, he has also gained a masters degree in Mathematics
from a reputed university. So, he wants Patrick to calculate the number of prime numbers (say P) up to M (i.e.
<= M). If Patrick calculates P, Teresa should call Red John on the phone number from the safe and he will
surrender if Patrick tells him the correct answer. Otherwise, Teresa will get another murder call after a week.

You are required to help Patrick correctly solve the puzzle.

Input Format

The first line of input will contain an integer T followed by T lines each containing an integer N.

Output Format

Print exactly one line of output for each test case. The output should contain the number P.

Constraints
1<=T<=20
1<=N<=40
TEST CASE 1

INPUT
2
1
7
OUTPUT
0
3
TEST CASE 2

INPUT
2
7
3
OUTPUT
3
0

#include <algorithm>
#include <cassert>

#include <cctype>

#include <cstdio>

#include <cstring>

#include <fstream>

#include <iostream>

#include <iterator>

#include <map>

#include <queue>

#include <set>

#include <string>

#include <utility>

#include <vector>

using namespace std;

#define MAX_VAL_ 300000

// 6bits = 1parity bit + 32 different offsets in the same int

int P_[(MAX_VAL_>>6) + 1]; // negative logic (1 bit marks a non-prime)

// ****** only call this for ODD x greater than 1 *****

inline bool is_prime_fast(int x) { return !((P_[x>>6]>>((x>>1)&0x1f))&1); }

// ****** only call this for ODD x greater than 1 *****

inline void mark_nonprime(int x) { P_[x>>6] |= (1<<((x>>1)&0x1f)); }

inline bool is_prime(int x) { return x==2 ? true : x<2||((x&1)==0) ? false : is_prime_fast(x); }

void init_primes() { for (long long x=3; x*x<=MAX_VAL_; x+=2) if (is_prime_fast(x)) { const long long z =
x<<1; for (long long y=x*x; y<=MAX_VAL_; y+=z) mark_nonprime(y); } }

int ways[41];

int main() {
init_primes();

int T;

cin >> T;

for (int testcase=0; testcase<T; ++testcase) {

int n;

cin >> n;

ways[0] = 1;

for (int i=1; i<=n; ++i) {

ways[i] = ways[i-1];

if (i >= 4) {

ways[i] += ways[i-4];

int sol = (ways[n]>=2);

for (int i=3; i<=ways[n]; i+=2) {

if (is_prime(i)) {

++sol;

cout << sol << '\n';

return 0;

Q. 50: The largest possible!


QUESTION DESCRIPTION

Array A contains the elements, A1,A2AN. A nd array B contains the elements, B1,B2BN.
There is a relationship between Ai and Bi, 1 i N, i.e., any element Ai lies between 1 and Bi. Let cost S of an
array A is defined as: image
You have to print the largest possible value of S.

Input Format

The first line contains, T, the number of test cases. Each test case contains an integer, N, in first line.

The second line of each test case contains N integers that denote the array B.

Output Format
For each test case, print the required answer in one line.

Constraints
1 <= T<= 20
1 <= N <= 105
1 <= Bi <= 100
TEST CASE 1

INPUT
1
5
10 1 10 1 10
OUTPUT
36
TEST CASE 2

INPUT
1
4
10 1 10 1
OUTPUT
27

#include<iostream>

#include<cmath>

#include<algorithm>

using namespace std;

int main()

int t; cin>>t;

while(t-- > 0) {

int n ;
cin>>n;

int b[10] ;

for(int i = 0; i < n; i++) {

cin>>b[i];

int dp[10][2]={0};

for(int i = 1; i < n; i++) {

dp[i][0] = max(dp[i-1][0], dp[i-1][1] + b[i-1]-1);

dp[i][1] = max(dp[i-1][0] + b[i]-1, dp[i-1][1] + abs(b[i]-b[i-1]));

cout<<max(dp[n-1][0], dp[n-1][1])<<endl;

return 0;

Q. 51: Permutations 1
QUESTION DESCRIPTION

Given alphabets i,j .Write a C Program to Generate All Permutations of the given alphabets using
BackTracking.
TEST CASE 1

INPUT
ij
OUTPUT
ij
ji
TEST CASE 2

INPUT
iiij
OUTPUT
iiij
iiji
iiij
iiji
ijii
ijii
iiij
iiji
iiij
iiji
ijii
ijii
iiij
iiji
iiij
iiji
ijii
ijii
jiii
jiii
jiii
jiii
jiii
jiii

#include <stdio.h>

#include <string.h>

void swap(char *x, char *y)

char temp;

temp = *x;

*x = *y;

*y = temp;

void permute(char *a, int l, int r)

int i;

if (l == r)

printf("%s\n", a);

else

for (i = l; i <= r; i++)


{

swap((a+l), (a+i));

permute(a, l+1, r);

swap((a+l), (a+i));

int main()

char str[100];

scanf("%s",str);

int n = strlen(str);

permute(str, 0, n-1);

return 0;

Q. 54: Word Boggle


QUESTION DESCRIPTION

Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character.
Find all possible words that can be formed by a sequence of adjacent characters.

Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same
cell.

Example:

Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};


boggle[][] = {{'G','I','Z'},
{'U','E','K'},
{'Q','S','E'}};

Output: Following words of dictionary are present GEEKS, QUIZ

Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test
case contains an integer x denoting the no of words in the dictionary.
Then in the next line are x space separated strings denoting the contents of the dictionary. In the next line are
two integers N and M denoting the size of the boggle. The last line of each test case contains NxM space
separated values of the boggle.

Output:
For each test case in a new line print the space separated sorted distinct words of the dictionary which could be
formed from the boggle. If no word can be formed print -1.

Constraints:
1<=T<=10
1<=x<=10
1<=n,m<=7

TEST CASE 1

INPUT
1
4
GEEKS FOR QUIZ GO
3 3
G I Z U E K Q S E
OUTPUT
GEEKS QUIZ
TEST CASE 2

INPUT
1
4
SRM UNIV KTR CSE
3 3
U S N R V M I
OUTPUT
SRM UNIV

#include <stdio.h>

#include<string.h>

#include<stdlib.h>

int strcmpfunc(const void *a, const void *b)

return (strcmp((char *)a, (char *)b));

int main()
{

int tst;

scanf("%d",&tst);

while(tst--)

int strings;

scanf("%d",&strings);

char str[strings][20];

int i;

for(i = 0; i<strings; i++)

scanf(" %s",str[i]);

/*Sort the array.*/

qsort(str, strings, sizeof(char)*20, strcmpfunc);

int pre_index = 0;

/*Remove duplicate*/

for(i = 1; i<strings; i++)

if (!strcmp(str[i], str[pre_index]))

str[i][0] = '\0';

else

pre_index = i;

int ch[82], str_ch[82], no_word = 1;


for(i = 0; i<82; i++)

ch[i] = 0;

str_ch[i] = 0;

int x, y, j;

scanf("%d", &x);

scanf("%d", &y);

for(j = 0; j<x*y; j++)

char input;

scanf(" %c", &input);

ch[input-'A']++;

for (i = 0; i<strings; i++)

if (!strlen(str[i]))

continue;

for(j = 0; j<82; j++)

str_ch[j] = 0;

for (j = 0; j<strlen(str[i]); j++)

str_ch[str[i][j]-'A']++;

for(j = 0; j<82; j++)

if (str_ch[j] && str_ch[j] > ch[j])


break;

if (j == 82)

printf("%s ",str[i]);

no_word = 0;

if (no_word)

printf("-1");

printf("\n");

return 0;

Q. 55: Chess 1
QUESTION DESCRIPTION

Chessboard queens can attack horizontally, vertically, and diagonally. The N-queens problem asks:

How can N queens be placed on an NxN chessboard so that no two of them attack each other?

Find a solution to the 4 queens problem.


TEST CASE 1

INPUT
4
OUTPUT
SOLUTION #1
* Q * *
* * * Q
Q * * *
* * Q *
SOLUTION #2
* * Q *
Q * * *
* * * Q
* Q * *
TOTAL SOLN. : 2
TEST CASE 2

INPUT
8
OUTPUT
SOLUTION #1
Q * * * * * * *
* * * * Q * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
SOLUTION #2
Q * * * * * * *
* * * * * Q * *
* * * * * * * Q
* * Q * * * * *
* * * * * * Q *
* * * Q * * * *
* Q * * * * * *
* * * * Q * * *
SOLUTION #3
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
* * Q * * * * *
SOLUTION #4
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
* * * * * Q * *
* * Q * * * * *
SOLUTION #5
* Q * * * * * *
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
SOLUTION #6
* Q * * * * * *
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
SOLUTION #7
* Q * * * * * *
* * * * Q * * *
* * * * * * Q *
* * * Q * * * *
Q * * * * * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
SOLUTION #8
* Q * * * * * *
* * * * * Q * *
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
* * * * * * * Q
* * Q * * * * *
* * * * Q * * *
SOLUTION #9
* Q * * * * * *
* * * * * Q * *
* * * * * * * Q
* * Q * * * * *
Q * * * * * * *
* * * Q * * * *
* * * * * * Q *
* * * * Q * * *
SOLUTION #10
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
* * * * Q * * *
Q * * * * * * *
* * * Q * * * *
SOLUTION #11
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
* * * * * * * Q
Q * * * * * * *
* * * Q * * * *
* * * * * Q * *
* * Q * * * * *
SOLUTION #12
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
* * * * * * Q *
* * * Q * * * *
SOLUTION #13
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
* * * * * Q * *
SOLUTION #14
* * Q * * * * *
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
* * * * * Q * *
SOLUTION #15
* * Q * * * * *
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
SOLUTION #16
* * Q * * * * *
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
SOLUTION #17
* * Q * * * * *
* * * * Q * * *
* * * * * * * Q
* * * Q * * * *
Q * * * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
SOLUTION #18
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * Q * * *
* * * * * * * Q
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
SOLUTION #19
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
Q * * * * * * *
* * * Q * * * *
* * * * * * * Q
* * * * Q * * *
SOLUTION #20
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
Q * * * * * * *
* * * * * * * Q
* * * Q * * * *
SOLUTION #21
* * Q * * * * *
* * * * * Q * *
* * * Q * * * *
Q * * * * * * *
* * * * * * * Q
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
SOLUTION #22
* * Q * * * * *
* * * * * Q * *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
SOLUTION #23
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
Q * * * * * * *
* * * Q * * * *
* * * * * * Q *
* * * * Q * * *
* Q * * * * * *
SOLUTION #24
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
Q * * * * * * *
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
SOLUTION #25
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
SOLUTION #26
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * * * Q
* * * * Q * * *
Q * * * * * * *
* * * Q * * * *
* * * * * Q * *
SOLUTION #27
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
Q * * * * * * *
* * * * Q * * *
SOLUTION #28
* * Q * * * * *
* * * * * * * Q
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * Q * * *
SOLUTION #29
* * * Q * * * *
Q * * * * * * *
* * * * Q * * *
* * * * * * * Q
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
SOLUTION #30
* * * Q * * * *
Q * * * * * * *
* * * * Q * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
SOLUTION #31
* * * Q * * * *
* Q * * * * * *
* * * * Q * * *
* * * * * * * Q
* * * * * Q * *
Q * * * * * * *
* * Q * * * * *
* * * * * * Q *
SOLUTION #32
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
Q * * * * * * *
* * * * Q * * *
SOLUTION #33
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
* * * * * * * Q
* * * * Q * * *
Q * * * * * * *
SOLUTION #34
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
Q * * * * * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
SOLUTION #35
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
SOLUTION #36
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
* * * * * * Q *
SOLUTION #37
* * * Q * * * *
* * * * * Q * *
Q * * * * * * *
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
* * Q * * * * *
* * * * * * Q *
SOLUTION #38
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
SOLUTION #39
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* Q * * * * * *
SOLUTION #40
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
* * * * * * * Q
* * * * Q * * *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
SOLUTION #41
* * * Q * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
Q * * * * * * *
* * * * * Q * *
SOLUTION #42
* * * Q * * * *
* * * * * * Q *
* * * * Q * * *
* Q * * * * * *
* * * * * Q * *
Q * * * * * * *
* * Q * * * * *
* * * * * * * Q
SOLUTION #43
* * * Q * * * *
* * * * * * Q *
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
SOLUTION #44
* * * Q * * * *
* * * * * * * Q
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
SOLUTION #45
* * * Q * * * *
* * * * * * * Q
Q * * * * * * *
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
SOLUTION #46
* * * Q * * * *
* * * * * * * Q
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
SOLUTION #47
* * * * Q * * *
Q * * * * * * *
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
SOLUTION #48
* * * * Q * * *
Q * * * * * * *
* * * * * * * Q
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
SOLUTION #49
* * * * Q * * *
Q * * * * * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
SOLUTION #50
* * * * Q * * *
* Q * * * * * *
* * * Q * * * *
* * * * * Q * *
* * * * * * * Q
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
SOLUTION #51
* * * * Q * * *
* Q * * * * * *
* * * Q * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * * * Q
* * * * * Q * *
Q * * * * * * *
SOLUTION #52
* * * * Q * * *
* Q * * * * * *
* * * * * Q * *
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
* * * * * * * Q
* * Q * * * * *
SOLUTION #53
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
Q * * * * * * *
* * * Q * * * *
* * * * * * Q *
* * Q * * * * *
* * * * * Q * *
SOLUTION #54
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
* * * * * * Q *
SOLUTION #55
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
SOLUTION #56
* * * * Q * * *
* * Q * * * * *
* * * * * * * Q
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
* * * * * Q * *
* Q * * * * * *
SOLUTION #57
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
* Q * * * * * *
SOLUTION #58
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
SOLUTION #59
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
* * * * * * * Q
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
SOLUTION #60
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * Q * * * *
* * * * * * * Q
SOLUTION #61
* * * * Q * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * * * * * Q
* * * Q * * * *
SOLUTION #62
* * * * Q * * *
* * * * * * Q *
* * * Q * * * *
Q * * * * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * Q * *
* Q * * * * * *
SOLUTION #63
* * * * Q * * *
* * * * * * * Q
* * * Q * * * *
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
SOLUTION #64
* * * * Q * * *
* * * * * * * Q
* * * Q * * * *
Q * * * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
SOLUTION #65
* * * * * Q * *
Q * * * * * * *
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
* * Q * * * * *
* * * * * * Q *
* * * Q * * * *
SOLUTION #66
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
* * * * * * * Q
* * * Q * * * *
SOLUTION #67
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
Q * * * * * * *
* * * Q * * * *
* * * * * * * Q
* * * * Q * * *
* * Q * * * * *
SOLUTION #68
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
SOLUTION #69
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * * * * * Q
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
SOLUTION #70
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * * * * * Q
* * * * Q * * *
* Q * * * * * *
* * * Q * * * *
* * * * * * Q *
SOLUTION #71
* * * * * Q * *
* * Q * * * * *
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
SOLUTION #72
* * * * * Q * *
* * Q * * * * *
* * * * Q * * *
* * * * * * * Q
Q * * * * * * *
* * * Q * * * *
* Q * * * * * *
* * * * * * Q *
SOLUTION #73
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
* * * * * * * Q
Q * * * * * * *
* * * * Q * * *
SOLUTION #74
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * * * * * Q
* * * * Q * * *
Q * * * * * * *
* * * Q * * * *
SOLUTION #75
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* * * Q * * * *
Q * * * * * * *
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
SOLUTION #76
* * * * * Q * *
* * * Q * * * *
Q * * * * * * *
* * * * Q * * *
* * * * * * * Q
* Q * * * * * *
* * * * * * Q *
* * Q * * * * *
SOLUTION #77
* * * * * Q * *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * Q * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
SOLUTION #78
* * * * * Q * *
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
* Q * * * * * *
* * * * * * * Q
SOLUTION #79
* * * * * Q * *
* * * Q * * * *
* * * * * * Q *
Q * * * * * * *
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
* * Q * * * * *
SOLUTION #80
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* * Q * * * * *
SOLUTION #81
* * * * * * Q *
Q * * * * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * Q * *
* * * Q * * * *
* Q * * * * * *
* * * * Q * * *
SOLUTION #82
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
Q * * * * * * *
* * * * * * * Q
* * * * Q * * *
* * Q * * * * *
* * * * * Q * *
SOLUTION #83
* * * * * * Q *
* Q * * * * * *
* * * * * Q * *
* * Q * * * * *
Q * * * * * * *
* * * Q * * * *
* * * * * * * Q
* * * * Q * * *
SOLUTION #84
* * * * * * Q *
* * Q * * * * *
Q * * * * * * *
* * * * * Q * *
* * * * * * * Q
* * * * Q * * *
* Q * * * * * *
* * * Q * * * *
SOLUTION #85
* * * * * * Q *
* * Q * * * * *
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
Q * * * * * * *
* * * * * Q * *
* * * Q * * * *
SOLUTION #86
* * * * * * Q *
* * * Q * * * *
* Q * * * * * *
* * * * Q * * *
* * * * * * * Q
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
SOLUTION #87
* * * * * * Q *
* * * Q * * * *
* Q * * * * * *
* * * * * * * Q
* * * * * Q * *
Q * * * * * * *
* * Q * * * * *
* * * * Q * * *
SOLUTION #88
* * * * * * Q *
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * Q * *
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
SOLUTION #89
* * * * * * * Q
* Q * * * * * *
* * * Q * * * *
Q * * * * * * *
* * * * * * Q *
* * * * Q * * *
* * Q * * * * *
* * * * * Q * *
SOLUTION #90
* * * * * * * Q
* Q * * * * * *
* * * * Q * * *
* * Q * * * * *
Q * * * * * * *
* * * * * * Q *
* * * Q * * * *
* * * * * Q * *
SOLUTION #91
* * * * * * * Q
* * Q * * * * *
Q * * * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * Q * * *
* * * * * * Q *
* * * Q * * * *
SOLUTION #92
* * * * * * * Q
* * * Q * * * *
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
TOTAL SOLN. : 92

#include<stdio.h>

#include<math.h>

int x[50],soln=0;

int place(int k,int i){


int j;

for(j=1;j<k;j++)

if((x[j]==i) || (abs(x[j]-i)==abs(j-k)))

return 0;

return 1;

void display(int n){

int i,j;

soln++;

printf("SOLUTION #%d\n",soln);

for(i=1;i<=n;i++){

for(j=1;j<=n;j++)

if(x[i]==j)

printf("Q ");

else

printf("* ");

printf("\n");

void nqueens(int k,int n){

int i;

for(i=1;i<=n;i++)

if(place(k,i)==1){

x[k]=i;

if(k==n)
display(n);

else

nqueens(k+1,n);

int main(){

int n;

// printf("Enter no. of queens : ");

scanf("%d",&n);

nqueens(1,n);

printf("TOTAL SOLN. : %d",soln);

return 0;

}
SESSION: Backtracking
Q. 57: Shortest Source to Destination Path
QUESTION DESCRIPTION

Given a boolean 2D matrix (0-based index), find whether there is path from (0,0) to (x,y) and if there is one
path, print the minimum no of steps needed to reach it, else print -1 if the destination is not reachable.

Input:

The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test
case contains two lines . The first line of each test case contains two integers n and m denoting the size of the
matrix.

Then in the next line are n*m space separated values of the matrix. The following line after it contains two
integers x and y denoting the index of the destination.

Output:
For each test case print in a new line the min no of steps needed to reach the destination.

Constraints:
1<=T<=100
1<=n,m<=20
TEST CASE 1

INPUT
2
3 4
1 0 0 0 1 1 0 1 0 1 1 1
2 3
3 4
1 1 1 1 0 0 0 1 0 0 0 1
0 3
OUTPUT
5
3
TEST CASE 2

INPUT
1
3 6
1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 1
0 5
OUTPUT
-1

#include<bits/stdc++.h>

using namespace std;

int n,m;

void s_to_d(int s_x,int s_y, int d_x,int d_y,int steps,int *min_step,int mat[30][30] )

// cout<<"hii";

if(s_x<0 || s_x >=n || s_y<0 || s_y >=m )

return;

else if(mat[s_x][s_y]==0)

return;

else

if(s_x==d_x && s_y ==d_y)

if(*min_step>steps)

*min_step=steps;

return;
}

mat[s_x][s_y]=0;

s_to_d(s_x-1,s_y,d_x,d_y,steps+1,min_step,mat);

s_to_d(s_x+1,s_y,d_x,d_y,steps+1,min_step,mat);

s_to_d(s_x,s_y-1,d_x,d_y,steps+1,min_step,mat);

s_to_d(s_x,s_y+1,d_x,d_y,steps+1,min_step,mat);

return;

int main()

int t,d_x,d_y;

int mat [30][30];

cin>>t;

while(t--)

cin>>n>>m;

for(int i=0;i<n;i++)

for(int j=0;j<m;j++)

cin>>mat[i][j];

cin>>d_x>>d_y;

int steps=0,min_step;

min_step=10000;

s_to_d(0,0,d_x,d_y,steps,&min_step,mat);
if(min_step==10000)

cout<<"-1\n";

else

cout<<min_step<<"\n";

return 0;

}
SESSION: Backtracking
Q. 58: Distance
QUESTION DESCRIPTION

Given a binary matrix of N x M, containing at least a value 1. The task is to find the distance of nearest 1 in the
matrix for each cell. The distance is calculated as |i1- i2| + |j1 - j2|, where i1, j1 are the row number and column
number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.

Examples:

Input : N = 3, M = 4
mat[][] = {
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
}
Output : 3 2 1 0
2100
1001

For cell at (0, 0), nearest 1 is at (0, 3), so distance = (0 - 0) + (3 - 0) = 3.

Similarly all the distance can be calculated.

Input:
The first line of input is an integer T denoting the no of test cases. Then T test cases follow. Each test case
consists of 2 lines . The first line of each test case contains two integers M and N denoting the no of rows and
columns of matrix . Then in the next line are N*M space separated values of the matrix (mat) .

Output:
For each test case in a new line print the required distance matrix in a single line separated by space.

Constraints:
1<=T<=20
1<=N,M<=20
TEST CASE 1

INPUT
2
2 2
1 0 0 1
1 2
1 1
OUTPUT
0 1 1 0
0 0
TEST CASE 2

INPUT
2
2 2
1 1 1 1
1 2
1 1
OUTPUT
0 0 0 0
0 0

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

struct cell

int x, y, value;

cell(int _x, int _y, int _value) : x(_x), y(_y), value(_value) {}

};

struct comp

bool operator() (cell &one, cell &two)

return one.value > two.value;

};

void solve(vector<vector<int>> &matrix)

{
priority_queue<cell, vector<cell>, comp> MYQ;

int X = matrix.size(), Y = matrix[0].size();

for(int x = 0; x < X; x++)

for(int y = 0; y < Y; y++)

if (matrix[x][y] == 1)

MYQ.push(cell(x, y, matrix[x][y]));

while (MYQ.size())

if (MYQ.top().x - 1 >= 0 && matrix[MYQ.top().x - 1][MYQ.top().y] == 0)

matrix[MYQ.top().x - 1][MYQ.top().y] = MYQ.top().value + 1;

MYQ.push(cell(MYQ.top().x - 1, MYQ.top().y, MYQ.top().value + 1));

if (MYQ.top().x + 1 < matrix.size() && matrix[MYQ.top().x + 1][MYQ.top().y] == 0)

matrix[MYQ.top().x + 1][MYQ.top().y] = MYQ.top().value + 1;

MYQ.push(cell(MYQ.top().x + 1, MYQ.top().y, MYQ.top().value + 1));

if (MYQ.top().y - 1 >= 0 && matrix[MYQ.top().x][MYQ.top().y - 1] == 0)

matrix[MYQ.top().x][MYQ.top().y - 1] = MYQ.top().value + 1;

MYQ.push(cell(MYQ.top().x, MYQ.top().y - 1, MYQ.top().value + 1));

}
if (MYQ.top().y + 1 < matrix.back().size() && matrix[MYQ.top().x][MYQ.top().y + 1] == 0)

matrix[MYQ.top().x][MYQ.top().y + 1] = MYQ.top().value + 1;

MYQ.push(cell(MYQ.top().x, MYQ.top().y + 1, MYQ.top().value + 1));

MYQ.pop();

for (int x = 0; x < X; x++)

for (int y = 0; y < Y; y++)

cout << matrix[x][y] - 1 << " ";

cout << endl;

int main()

int T, x, y;

cin >> T;

vector<vector<int>> matrix;

while (T--)

cin >> x >> y;

matrix.clear();

matrix.resize(x, vector<int>(y));
for(int a = 0; a < x; a++)

for (int b = 0; b < y; b++)

cin >> matrix[a][b];

solve(matrix);

SESSION: Graph Colouring


Q. 61: Minimum Spanning Tree-Pilgrims and Portals
QUESTION DESCRIPTION

Pritam is a priest in his village. He needs to pay his respects to k shrines which his all ancestors have visited
and had asked their successors to pay the respect. But he hates walking so he wants to minimize the distance he
has to travel to pay his respects.

As he is busy packing he asks you to help him. He has acquired a bunch of portal scrolls through which he can
create portal networks. Portals can only be created at shrines , and after entering a portal a he can exit at any
desired portal.

You have to give the minimum distance Pritam has to travel. There are number of cities which dont have
shrines but that can be traveled through.
You will be given n the number of cities and out of which first k cities have shrines.

There is road connecting two cities which will be defined by three integers a, b and c where a and b are the
cities and c is the distance between the cities.

You have to calculate the minimum distance that need to be walked for this pilgrimage given that there is no
restriction on number of portals that can be created but need to be created at shrines.
After you have told him the distance hell decide whether its worth undertaking or not. You can assume that he
starts from 1st city.

[Input]
First line contains integer t denoting number of test cases.
First line of every test case consists of 3 integers n, m and k denoting number of cities, number of roads and
number of shrines respectively.
Next m lines of test case consists of 3 space separated integers a, b and c, where a and b are cities and c is the
distance between them.

[Output]
For each test case print a single integer containing the minimum distance he need to walk for the pilgrimage.
[Constraints]
1<=t<=20
1<=n<=100
n-1<=m<=(n*(n-1))/2
1<=k<=n
1<=a,b<=n
1<=c<=1000000
TEST CASE 1

INPUT
1
5 10 3
1 2 10
1 3 5
1 4 10
1 5 80
2 3 9
2 4 1
2 5 20
3 4 100
3 5 2
4 5 20
OUTPUT
14
TEST CASE 2

INPUT
1
5 10 3
1 2 10
1 3 5
OUTPUT
15

#include<stdio.h>

#define INF 100000000000000

int x[200],done[200];

long long dist[200][200],graph[200][200];

void floyd (int n)

int i, j, k;

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)


dist[i][j] = graph[i][j];

for (k = 0; k < n; k++)

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

if (dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

int main()

int n,m,a,b,i,j;

FILE *p=stdin;

int t;

long long c;

fscanf(p,"%d",&t);

while(t--)

int z=0,k;

long long ans=0;

fscanf(p,"%d%d%d",&n,&m,&k);

for(i=0; i<n; i++)

for(j=0; j<n; j++)


graph[i][j]=0;

while(m--)

fscanf(p,"%d %d %lld",&a,&b,&c);

graph[a-1][b-1]=c;

graph[b-1][a-1]=c;

for(i=0; i<n; i++)

for(j=0; j<n; j++)

if(graph[i][j]==0&&i!=j)

graph[i][j]=INF;

floyd(n);

x[0]=1;

x[1]=0;

dist[0][0]=INF;

for(i=0;i<n;i++)

done[i]=0;

done[0]=1;

for(i=1;i<k;i++)

int ans1=0,ans2=0;

for(j=1;j<=x[0];j++)

for(z=1;z<k;z++)

if(!done[z]&&dist[x[j]][z]<dist[ans1][ans2])

ans1=x[j],ans2=z;
}

x[++x[0]]=ans2;

done[ans2]=1;

ans+=dist[ans1][ans2];

printf("%lld\n",ans);

return 0;

SESSION: Graph Colouring


Q. 62: Jack goes to Rapture
QUESTION DESCRIPTION

Jack has just moved to a new city called Rapture. However, he is confused by Rapture's public transport
system. The rules of the public transport are as follows:

Every pair of connected stations has a fare assigned to it.

If a passenger travels from station A to station B, he only has to pay the difference between the fare from A to
B and the cumulative fare that he has paid to reach station A [fare(A,B) - total fare to reach station A]. If the
difference is negative, he can travel free of cost from A to B.

Since Jack is new to the city, he is unemployed and low on cash. He needs your help to figure out the most
cost efficient way to go from the first station to the last station. You are given the number of stations N, and
the fare between the E pair of stations that are connected.

Input Format

The first line contains two integers, N and E, followed by E lines containing three integers each: the two
stations that are connected to each other and the fare between them (C).

Constraints

1<=N<=50000
1<=E<=500000
1<=C<=10^7

Output Format

The minimum fare to be paid to reach station N from station 1. If the station N cannot be reached from station
1, print "NO PATH EXISTS" (without quotes).
TEST CASE 1

INPUT
5 5
1 2 60
3 5 70
1 4 120
4 5 150
2 3 80
OUTPUT
80
TEST CASE 2

INPUT
4 4
1 2 60
2 3 10
1 4 20
3 4 30
OUTPUT
20

#include <math.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define inf 100000000

#include<bits/stdc++.h>

#define ff first

using namespace std;

#define ss second

#define mp make_pair

#define pp pair<int,int>

#define pb push_back

#define ll long long int

#define vil vector<ll>

#define vi vector<int>

#define vip vector<pair<int,int> >

#define vipl vector<pair<ll,ll> >


#define mod 1000000007

int dist[100010];

list<pair<int,int> > arr[100010];

int read_int1(){

char r;

bool start=false,neg=false;

long long int ret=0;

while(true){

r=getchar();

if((r-'0'<0 || r-'0'>9) && r!='-' && !start){

continue;

if((r-'0'<0 || r-'0'>9) && r!='-' && start){

break;

if(start)ret*=10;

start=true;

if(r=='-')neg=true;

else ret+=r-'0';

if(!neg)

return ret;

else

return -ret;

long long int read_int2(){

char r;

bool start=false,neg=false;

long long int ret=0;


while(true){

r=getchar();

if((r-'0'<0 || r-'0'>9) && r!='-' && !start){

continue;

if((r-'0'<0 || r-'0'>9) && r!='-' && start){

break;

if(start)ret*=10;

start=true;

if(r=='-')neg=true;

else ret+=r-'0';

if(!neg)

return ret;

else

return -ret;

class Prioritize

public:

int operator() ( const pair<int,int>& p1, const pair<int,int>& p2 )

return p1.second > p2.second;

};

void dfs(int st)

dist[st]=0;
priority_queue<pp, vector<pp > , Prioritize > Q;

Q.push(mp(st,0));

while(!Q.empty())

//auto t=Q.top();

int n=Q.top().ff;

Q.pop();

list<pair<int,int> > ::iterator it;

for(it=arr[n].begin();it!=arr[n].end();it++)

ll cost=max(it->ss,dist[n]);

if(dist[it->ff]>cost)

dist[it->ff]=cost;

Q.push(mp(it->ff,dist[it->ff]));

int main()

int n;

int m;

cin>>n>>m;

int a,b;

int c;
for(int i=0;i<m;i++)

a=read_int1();

b=read_int1();

c=read_int1();

arr[a].pb(mp(b,c));

arr[b].pb(mp(a,c));

for(int i=1;i<=n;i++)

dist[i]=inf;

dfs(1);

if(dist[n]==inf)

cout<<"NO PATH EXISTS "<<endl;

else

cout<<dist[n]<<endl;

return 0;

SESSION: Graph Colouring


Q. 63: Monk Learning Graph
QUESTION DESCRIPTION

Monk once went to the graph city to learn graphs, and meets an undirected graph having N nodes, where each
node have value val[i] where 1<=i<=N. Each node of the graph is very curious and wants to know something
about the nodes which are directly connected to the current node.

For each node, if we sort the nodes (according to their values), which are directly connected to it, in
descending order (in case of equal values, sort it according to their indices in ascending order), then what will
be the number of the node at kth position, if positions are given starting from 1.

Note: If the values are same , then sort it . Now Graph gave this task to Monk. Help Monk for the same.

Input Format :
The first line will consist of 3 space separated integers N,M, k denoting the number of nodes, number of edges
and value of k respectively.

In next line, there will be N space separated integers, val[i] , where 1<= i<= N, denoting the value of ith node.

In next M lines, each line contains 2 integers X and Y, representing an edge between X and Y.

Output Format
Print N lines, where ith line contains the required node for the ith node. If there is no such node, print -1.

Constraints: :

1 <=N <=10^3
1 <=M <=10^6
1<= k<= M
1 <=val[i] <=10^4
1<= X,Y<= N
TEST CASE 1

INPUT
3 3 2
2 4 3
1 3
1 2
2 3
OUTPUT
3
1
1
TEST CASE 2

INPUT
3 3 2
2 3 3
1 3
1 2
2 3
OUTPUT
2
1
1

#include <bits/stdc++.h>

#define ll long long

using namespace std;

const int ma = 1e5+5;

vector < pair <int, int > > v[1005];

int w[1005];
int main()

/*freopen("si.txt","r",stdin);

freopen("so.txt","w",stdout);*/

//n,k = 1000

//m = 1e6

//w[i] = 100000

int n,m,k;

cin>>n>>m>>k;

for(int i=1;i<=n;i++)

cin>>w[i];

int x,y;

for(int i=0;i<m;i++)

cin>>x>>y;

v[x].push_back(make_pair(w[y],y));

v[y].push_back(make_pair(w[x],x));

for(int i=1;i<=n;i++)

sort(v[i].begin(), v[i].end());

for(int i=1;i<=n;i++)

if(v[i].size()>=k)

cout<<v[i][v[i].size()-k].second<<endl;

else

cout<<"-1"<<endl;

return 0;
}

SESSION: Graph Colouring


Q. 65: DFS-Feasible relations
QUESTION DESCRIPTION

As a programmer, you sometimes have to deal with some math and this is the time to do it. You are given a list
of binary relations, equalities and inequalities, like a = b, a != d, b = c etc.

Your task is to output YES if you can assign integers to input variables in such a way, that you can satisfy all
equalities and inequalities. Otherwise you should output NO.

Input format:

In the first line there is one integer T denoting the number of test cases. Description of T test cases follow.

Each one have two integers N and K given in the first line denoting the number of variables and the number of
relations between them for this test case. All variables are represented by integers in range [1, N]. K lines
follow.

Each of them is of the form "x1 R x2" where x1 and x2 are integers representing variables and R is either "="
or "!=" and denotes the kind of relation between these variables.

Output format:

Output exactly T lines. In i-th of them, output the answer to the i-th test case.

Constraints:

T <= 10
1 <= N, K <= 10^6

Sum of N in one test file does not exceed 10^6


Sum of K in one test file does not exceed 10^6
TEST CASE 1

INPUT
2
2 2
1 = 2
1 != 2
3 2
1 = 2
2 != 3
OUTPUT
NO
YES
TEST CASE 2

INPUT
3
3 2
1 = 2
2 != 3
2 2
1 = 2
1 != 2
2 != 3
2 3
1 = 2
1 != 3
OUTPUT
YES
NO
YES

#include<bits/stdc++.h>

using namespace std;

#define sf(a) scanf("%d",&a);

#define sfc(a) scanf("%c",&a);

#define pf(a) printf("%d\n",a);

vector<int > v[1000001];

vector<pair<int ,int > > c;

bool visited1[1000001];

int cnt,value[1000001];

void dfs1(int x){

visited1[x]=true;

value[x]=cnt;

for(int i=0;i<v[x].size();i++){

if(visited1[v[x][i]]==false)

dfs1(v[x][i]);

return;

}
int main()

int t;

sf(t)

while(t--){

int n,k;

sf(n)

sf(k)

int i,source1,j;

for(i=0;i<k;i++){

int x1,x2;

string s;

sf(x1);

cin>>s;

sf(x2);

//cout<<x1<<s<<x2<<"\n";

if(s=="="){

source1=x1;

v[x1].push_back(x2);

v[x2].push_back(x1);

else{

c.push_back(make_pair(x1,x2));

cnt=1;
for(i=1;i<=n;i++){

if(!visited1[i])

dfs1(i);

cnt++;

cnt=0;

for(i=0;i<c.size();i++){

if(value[c[i].first]==value[c[i].second]){

cnt=1;

break;

if(cnt==0)

printf("YES");

else

printf("NO");

printf("\n");

c.clear();

for(i=1;i<=n;i++){

visited1[i]=false;

v[i].clear();

}
return 0;

SESSION: Graph Colouring


Q. 67: BFS-Sonya and the graph with disappearing edges
QUESTION DESCRIPTION

Pussycat Sonya is standing on the graph in the node with number 1 and she wants to reach the node number N.
It's known that graph consists of N nodes and M undirected edges. Getting through the edge takes 1 unit of
time.

It's also known that there are K moments of time in which some edges will disappear. Let's consider this
process in more detail. Sonya stands in the node number 1 at the moment of time = 0.

Moving to any of adjacent nodes through the edge increases time by 1 unit. And once she changed her location
all edges that must disappear at that moment of time become unavailable.

What is the minimal time Sonya needs to reach the node number N? If it's impossible print -1.

Input:

The first line of input contains three integers N - the number of nodes, M - the number of edges and K - the
number of moments of time in which some edges will disappear.

Each of the next M lines contains a pair of integers Ui and Vi which means that edge number i connects node
number Ui and node number Vi. You can assume that between any pair of nodes there's no more than one
connecting edge and there's no edge connecting some node to itself.

Then K lines follow. Each of these lines contains a pair of integers T and X which means that at moment of
time T the edge number X will disappear. You can assume that all Xs will be unique.

Output:
Print the minimal time Sonya needs to reach the node number N, if it's impossible print -1.

Constraints:
1<= N <= 10^5
0 <= K <= M <= min((N * (N - 1)) / 2, 10^5)
1<= Ui, Vi <= N
1 <= T <= 10^9
1 <= X <= M
TEST CASE 1

INPUT
5 5 1
1 2
1 3
2 5
3 4
4 5
1 3
OUTPUT
3
TEST CASE 2

INPUT
7 7 1
1 2
2 3
1 4
3 6
5 4
7 5
6 7
2 6
OUTPUT
4

#include<bits/stdc++.h>

#define bs 1000000007

using namespace std;

int n,m,k,a[1<<20],b[1<<20];

int live[1<<20];

queue<int> qu;

int dist[1<<20];

vector<int> g[1<<20];

int get_vertex(int edge,int v)

if (a[edge]==v)

return b[edge];

return a[edge];

int main(){

cin>>n>>m>>k;

for (int i=0;i<m;i++)

cin>>a[i]>>b[i];
g[a[i]].push_back(i);

g[b[i]].push_back(i);

live[i]=1e9;

for (;k;--k)

int a,b;

cin>>a>>b;

--b;

live[b]=a;

for (int i=1;i<=n;i++)

dist[i]=1e9;

qu.push(1);

dist[1]=0;

while (qu.size())

int id=qu.front();

qu.pop();

for (int i=0;i<g[id].size();i++)

int edge=g[id][i];

if (live[edge]<=dist[id])

continue;

int to=get_vertex(edge,id);

if (dist[to]>dist[id]+1)

dist[to]=dist[id]+1;
qu.push(to);

if (dist[n]>1e5)

dist[n]=-1;

cout<<dist[n]<<endl;

return 0;}
SESSION: Graph Colouring
Q. 68: BFS-The Witches of HEgwarts!
QUESTION DESCRIPTION

Little PandeyG is a curious student, studying in HEgwarts. Being smarter, faster and displaying more zeal for
magic than any other student, one by one he managed to impress the three hidden witches of the school.

They knew his secret desire to be a warrior, so each of them gave him some super power to use if he's up for a
fight against one of his enemies.

The first witch: She gave PandeyG the power to take away one unit of strength away from his enemies. - Eg
361=35.
The second witch: Jealous of the first witch, the second one gave the kid the power to halfen the strength of his
enemies. - Eg. 362=18.
The third witch: Even better, she gave him the power to reduce the strength of his enemies to one third of what
it initially was. - Eg. 363=12.

The witches, though, clearly told him that he'll be only able to use these powers if the strength of the opponent
is an integer, otherwise not.

Since, PandeyG is one smart kid, he knew that by using all three of the powers he has got, he'll be able to
defeat every enemy he's ever going to face, sometime or the other, in some number of moves.

Now, here's the twist: In spite of having all these powers, PandeyG was still losing matches against his
enemies - because he was unable to use them in the optimal fashion. To defeat an opponent, you need to make
sure that the enemy has only 1 unit of strength left in him.

Given the value k' - k being the units of the enemy of PandeyG's strength, help PandeyG figure out the
minimum number of magical hits he'll be needing to defeat his opponent, using his powers.

Input Format: The first line represents the number of test cases, t. Followed by t lines - and on every line, a
number n - with the strength unit of your enemy.

Output format: For every number n, print the minimum number of hits needed to defeat his enemy by making
his strength equal to 1.

Constraints:
1<=t<=1000
1<=n<=10^9
TEST CASE 1

INPUT
5
1
2
3
4
5
OUTPUT
0
1
1
2
3
TEST CASE 2

INPUT
1
10
OUTPUT
3
Problem with Question? Report

#include<stdio.h>

int a[100000];

void preprocess(){

int i=0;

a[1]=0;

a[2]=1;

a[3]=1;

int x,y;

for(i=4;i<100000;i++){

x = a[i/3]+i%3+1;

y = a[i/2]+i%2+1;

if(x > y)

a[i]= y;

else
a[i]=x;

int ans(int input)

int x, y;

if (input <= 1)

return 0;

if(input<100000){

return a[input];

x = ans(input/3)+input%3+1;

y = ans(input/2)+input%2+1;

if(x > y)

return y;

else

return x;

int main()

preprocess();

int cases, input, count, x, y;

scanf("%d", &cases);

while(cases--) {

scanf("%d", &input);

count = 0;

if (input > 1) {
x = ans(input/3)+(input%3)+1;

y = ans(input/2)+(input%2)+1;

if (x > y)

printf("%d\n", y);

else

printf("%d\n", x);

else

printf("0\n");

}
SESSION: Graph Colouring
Q. 69: DFS-Jungle Run
QUESTION DESCRIPTION

You are lost in a dense jungle and it is getting dark. There is at least one path that leads you to the city on the
other side but you cannot see anything until you are right in front of it as the trees and bushes obscure the path.

Devise an algorithm that is guaranteed to find the way out. Your goal is to go out of the jungle as fast as you
can before it gets dark.

[Input]:
Input start with a number N and then the matrix of size N x N filled with S, E, T, and P which is our map. Map
contains a single S representing the start point, and single E representing the end point and P representing the
path and T representing the Tree.

[Output]:
output single integer i.e. minimum number of moves from S to E.

Assumptions:

You can assume that the maps would be in square form and can be up to a maximum size of 30X30. You can
move in four directions North East West South.
You can move in any direction when you find P but cannot move to a point where a T is present.

*Problem provided by JDA


TEST CASE 1

INPUT
5
S P P P P
T P T P P
T P P P P
P T E T T
P T P T T
OUTPUT
5
TEST CASE 2

INPUT
14
S P P P P P P T P T P P P P
P P T P T P T P P E P T T P
T T P P P T P T P T T P P T
P P P T P T T P P P P P T P
P P T P P P P T P T T P P T
T T P T P T P P T P T P T P
P P P P P T P T P P P P P P
T P T P T P P P T P T P T T
T T P T T P T T P P P T P T
P P T P P P T P T P T P P P
P T P P T T P T T P T P P T
T P T P T P P P P P P P T P
P T P P P P T P P T P T P T
P P T P T P P T T P P P T P
OUTPUT
44

#include <stdio.h>

#include <limits.h>

#define UP 1

#define DOWN 2

#define LEFT 3

#define RIGHT 4

int mat[30][30];

int min=INT_MAX,n;

char arr[30][30];

void minPath(int i,int j,int status,int k)

if(arr[i][j]=='T')

return;
}

if(arr[i][j]=='E')

if(k<min)

min=k;

else

return;

if(mat[i][j])

if(k<mat[i][j])

mat[i][j]=k;

else

return;

else

mat[i][j]=k;

if(i-1>=0 && status!=DOWN) //UP

minPath(i-1,j,UP,k+1);

if(i+1<n && status!=UP) //DOWN

minPath(i+1,j,DOWN,k+1);
}

if(j-1>=0 && status!=RIGHT) //LEFT

minPath(i,j-1,LEFT,k+1);

if(j+1<n && status!=LEFT) //RIGHT

minPath(i,j+1,RIGHT,k+1);

int main(void) {

int i,j,iE,jE;

char c;

scanf("%d",&n);

c=getchar();

for(i=0;i<n;i++)

for(j=0;j<n;j++)

arr[i][j]=getchar();

c=getchar();

if(arr[i][j]=='S')

mat[i][j]=0;

iE=i;

jE=j;

}
}

if(iE-1>=0) //UP

minPath(iE-1,jE,UP,1);

if(iE+1<n ) //DOWN

minPath(iE+1,jE,DOWN,1);

if(jE-1>=0) //LEFT

minPath(iE,jE-1,LEFT,1);

if(jE+1<n ) //RIGHT

minPath(iE,jE+1,RIGHT,1);

printf("%d",min);

return 0;

QUESTION
SESSION: String Matching
Q. 71: Knuth-Morris-Pratt algorithm for Pattern Matching
QUESTION DESCRIPTION

Write a C program to implement KnuthMorrisPratt algorithm.


Knuth-Morris-Pratt(KMP) is a string matching algorithm.

It helps to find the search string in the given target string with minimal comparisons.

For the target string of length n and patter string of length m, the running time of the KMP algorithm is
O(m+n).

KMP algorithm involves two phases. They are finding the overlap in the pattern and finding pattern in target
string.
How to find the overlap in the given pattern?

Here, we need to find suffix(in the pattern) that matches prefix of the given pattern. For example, "abcdabd" is
the input string. "ab" at the end is the suffix that matches the prefix "ab" at the start => abcdabd
TEST CASE 1

INPUT
C is a Programming Language
is a
OUTPUT
is a located at the index 3
TEST CASE 2

INPUT
THIS IS A TEST TEXT
TEST
OUTPUT
TEST located at the index 11

import java.io.*;

import java.util.*;

public class TestClass {

public static void search(String txt, String pat)

int M = pat.length();

int N = txt.length();

for (int i = 0; i <= N - M; i++) {

int j;

for (j = 0; j < M; j++)

if (txt.charAt(i + j) != pat.charAt(j))

break;
if (j == M)

System.out.println(pat+" located at the index "+(i+1));

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String txt =s.nextLine();

String pat = s.nextLine();

//System.out.println(txt+" "+pat);

search(txt, pat);

}
SESSION: String Matching
Q. 72: Ristha's Pangrams
QUESTION DESCRIPTION

Ristha is 3 years old. She is very intelligent. She found a sentence "The quick brown fox jumps over the lazy
dog" in her story book. She noticed that this sentence contains all the alphabets in English.

She told this to her mom. Mom told her that this sentence is a Pangram (Pangrams are sentences constructed
by using every letter of the alphabet at least once.)

She got really interested in this. She started checking every sentences she go through. She got tired after a
while..
Given a sentence s, help Ristha to check if it is a pangram or not.

Input Format

Input consists of a string s.

Constraints
Length of s can be at most 10^3(1<=|s|<=10^3) and it may contain spaces, lower case and upper case letters.
Lower-case and upper-case instances of a letter are considered the same.

Output Format

Output a line containing pangram if s is a pangram, otherwise output not pangram.


TEST CASE 1

INPUT
We promptly judged antique ivory buckles for the next prize
OUTPUT
pangram
TEST CASE 2

INPUT
We promptly judged antique ivory buckles for the prize
OUTPUT
not pangram

#include <iostream>

#include <string>

using namespace std;

int main()

string inputString;

getline(cin, inputString);

int alphabetTab = 0;

int alphabet[26];

int flag = 0;

for(int i = 0; i < 26; i++){

alphabet[i] = 0;

for(int i = 0; i < inputString.length(); i++){

int insertNum = (tolower(inputString[i]) - 'a');

if(insertNum < 0 || insertNum > 25){

continue;

if(alphabet[insertNum] == 0){

alphabetTab++;

if(alphabetTab >= 26){


flag = 1;

break;

} else {

alphabet[insertNum]++;

if(flag){

cout << "pangram" << endl;

} else {

cout << "not pangram" << endl;

return 0;

}
SESSION: String Matching
Q. 73: Mia and String Matching
QUESTION DESCRIPTION

Mia in a Tech competition was assigned a task for writing a function to determine how closely two words
resemble each other.

How will Mia do this task?

Example, the words "TICK" and "TOCK" have a score of 3, since three characters (T, C, K) are the same.

Similarly, "CAT" and "DOG" score 0, since no letters match.

You are given Strings A and B and you have to return an integer K indicating the score (as defined above) of
how closely the two match.

Input :

First line of input contains an integer T denoting the number of test cases. Each test case contains two lines of
input, where first line contains the string A and second line contains the string B.

Output :
For each test case print the score on a line.

Constraints :

A and B will each contain between 1 and 500 characters, inclusive.


Each character of a and b will be 'A'-'Z'.
1 <= T <= 50
TEST CASE 1

INPUT
3
TICK
TOCK
CAT
DOG
APPLE
APPLES
FANTASTIC
ANTASTIC
OUTPUT
3
0
5
TEST CASE 2

INPUT
4
TICK
TOCK
CAT
DOG
APPLE
APPLES
FANTASTIC
ANTASTIC
OUTPUT
3
0
5
0

#include <iostream>

#include <string.h>

using namespace std;

int main()

{
int T;

cin >> T;

while(T--)

string a,b;

int x,y,i,count=0;

cin >> a;

cin >> b;

x=a.length();

y=b.length();

if(y>x)

for(i=0 ; i<x ; i++)

if(a[i]==b[i])

count+=1;

cout << count << endl;

else

for(i=0 ; i<y ; i++)

if(a[i]==b[i])

count+=1;

cout << count << endl;

}
}

return 0;

}
SESSION: String Matching
Q. 74: Ram and Wow String
QUESTION DESCRIPTION

Ram says that a Wow String is a string that only contains vowels (a,e,i,o,u).

Now, his teacher gave him a string S. He is wondering what is the length of the longest Wow string which is a
substring of S.

Note: Strings contains only lower case English Alphabets.

Input:

First line contains a string S,


(1<=|S|<=10^5), where |S| denotes the length of the string.

Output:
Print an integer denoting the length of the longest good substring, that is substring consists of only vowels.
TEST CASE 1

INPUT
abcaac
OUTPUT
2
TEST CASE 2

INPUT
uytqthfcjraawtb
OUTPUT
2

#include <iostream>

using namespace std;

bool isvowel(char s){

return s=='a' || s=='e' || s=='i' || s=='o'|| s=='u';

int main()

{
string s;

cin>>s;

int n = s.length();

int cnt=0, ans=0;

for(int i=0;i<n;i++){

if(isvowel(s[i])){

cnt=0;

while(isvowel(s[i]) && i<n){

cnt++;

i++;

i--;

if(cnt>ans)

ans = cnt;

cout<<ans;

return 0;

Q. 75: Compare
QUESTION DESCRIPTION

C program to compare two strings


Input format:

Enter two strings to be compared

Output format:
Compare the two strings and print
"Entered strings are equal." if they are equal else
"Entered strings are not equal."
TEST CASE 1

INPUT
HAI
hai
OUTPUT
Entered strings are not equal.
TEST CASE 2

INPUT
HAI
HAI
OUTPUT
Entered strings are equal.

#include <iostream>

#include <string.h>

using namespace std;

int main() {

char str1[20],str2[30];

cin>>str1>>str2;

int res = strcmp(str1,str2);

if(res==0)

cout<<"Entered strings are equal.";

else

cout<<"Entered strings are not equal.";

return 0;

}
SESSION: String Matching
Q. 76: String Matching Using String Library
QUESTION DESCRIPTION

C program to compare two strings using strcmp


TEST CASE 1

INPUT
HAI
hai
OUTPUT
Entered strings are not equal
TEST CASE 2

INPUT
HAI
HAI
OUTPUT
Entered strings are equal

#include <iostream>

#include <string>

using namespace std;

int main() {

string str1,str2;

cin>>str1>>str2;

if(str1==str2)

cout<<"Entered strings are equal";

else

cout<<"Entered strings are not equal";

return 0;

SESSION: String Matching


Q. 77: Dynamic Programming:Longest Common Subsequence
QUESTION DESCRIPTION

LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of
them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.

For example, "abc", "abg","bdf", "aeg", "acefg", .. etc are subsequences of "abcdefg".

So a string of length n has 2^n different possible subsequences.


TEST CASE 1

INPUT
ABCDGH
AEDFHR
OUTPUT
Length of LCS is 3
TEST CASE 2

INPUT
AGGTAB
GXTXAYB
OUTPUT
Length of LCS is 4
#include<bits/stdc++.h>

#include<iostream>

#include <string>

using namespace std;

int max(int a, int b);

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */

int lcs( char *X, char *Y, int m, int n )

if (m == 0 || n == 0)

return 0;

if (X[m-1] == Y[n-1])

return 1 + lcs(X, Y, m-1, n-1);

else

return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

/* Utility function to get max of 2 integers */


int max(int a, int b)

return (a > b)? a : b;

/* Driver program to test above function */

int main()

int m,n;

char X[101];

char Y[101];

cin>>X;

cin>>Y;

m = strlen(X);

n = strlen(Y);

printf("Length of LCS is %d", lcs( X, Y, m, n ) );

return 0;

SESSION: String Matching


Q. 78: Playful String
QUESTION DESCRIPTION

KillCode is trying to learn strings but failing to solve the recursive approach given by his Teacher. His Teacher
gave him a string consisting of lower case alphabets only , He asked to find a substring in the given string after
removing any characters from the original string .

For example if the string is

" Cypher" and the substring is "yer", Kill code can remove p,h from the string and can form the given
substring.
Now the Teacher got impressed from Killcode and decided to increase the difficulty by asking to find the
substring and reverse of substring in given string. If both substring can be formed by a given string by
removing certain characters , print "GOOD STRING " else print "BAD STRING".

Contraints

1<=t<=10
1<=|s|<=100000

Input -
First line contains integer t denoting the test cases, each test case contains two lines containing two strings.

Output-
Print "GOOD STRING"(without quotes) both strings can be formed by given string else print "BAD
STRING".
TEST CASE 1

INPUT
2
Srm
srmaba
oley
le
OUTPUT
BAD STRING
BAD STRING
TEST CASE 2

INPUT
3
abta
aba
oley
le
tereo
re
OUTPUT
GOOD STRING
BAD STRING
GOOD STRING
#include <stdio.h>

#include <string.h>

#include <stdbool.h>

char str[100000],sub[100000];

bool isSubstring()

{
int i=0,j=0;

while(str[i]!='\0' && sub[j]!='\0'){

if(str[i]==sub[j]){

i++;

j++;

else

i++;

if(j==strlen(sub))

return true;

return false;

int main()

int t,i,j,k;

char ch;

scanf("%d",&t);

for(i=1;i<=t;i++){

scanf("%s",str);

scanf("%s",sub);

if(isSubstring()){

j=0;

k=strlen(sub)-1;

while(j<k){

char ch=sub[j];

sub[j]=sub[k];

sub[k]=ch;
j++;

k--;

if(isSubstring())

printf("GOOD STRING");

else

printf("BAD STRING");

else

printf("BAD STRING");

printf("\n");

return 0;

}
SESSION: String Matching
Q. 79: Naive Pattern Searching
QUESTION DESCRIPTION

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all
occurrences of pat[] in txt[]. You may assume that n > m.

Examples:

Input: txt[] = "THIS IS A TEST TEXT"


pat[] = "TEST"

Output: Pattern found at index 10

Input: txt[] = "AABAACAADAABAABA"


pat[] = "AABA"

Output: Pattern found at index 0


Pattern found at index 9
Pattern found at index 12
TEST CASE 1

INPUT
THIS IS A TEST TEXT
TEST
OUTPUT
Pattern found at index 10
TEST CASE 2

INPUT
AABAACAADAABAAABAA
AABA
OUTPUT
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13

#include <stdio.h>

#include<string.h>

void search(char pat[],char txt[])

int M=strlen(pat);

int i,j;

int N=strlen(txt);

for(i=0;i<N-M+1;i++)

for(j=0;j<M;j++)

if(txt[i+j]!=pat[j])

break;

if(j==M)

printf("Pattern found at index %d\n",i);

int main()

char txt[30],pat[30];

fgets(txt,30,stdin);

fgets(pat,30,stdin);

search(pat,txt);

return 0;
}

SESSION: String Matching


Q. 80: Joy And Two Strings
QUESTION DESCRIPTION

Joy has two strings S1 and S2 both consisting of lower case alphabets. He listed all subsequences of string S1
on a paper and all subsequences of string S2 on a separate paper. He wants to know whether there exists a
string which is listed on both the papers.

Help Joy to accomplish this task.

Input

First line of input contains a single integer T denoting the number of test cases. Each test case consists of two
lines.

First line of each test case contains a string denoting string S1. Next line of each test case contains a string
denoting string S2.

Output

For each test case, Print Yes if both papers contain a common string otherwise Print No.

Constraints

1 <= T <= 10^5

1 <= |S1| <= 10^5

1 <= |S2| <= 10^5

Sum of |S1| over all test case does not exceed 5*10^5

Sum of |S2| over all test case does not exceed 5*10^5

Subtasks

Subtask1 : sum of |S1|,|S2| over all test cases does not exceed 10^3 (25 pts)
Subtask2 : sum of |S1|,|S2| over all test cases does not exceed 10^4 (25 pts)
Subtask3 : sum of |S1|,|S2| over all test cases does not exceed 5*10^5 (50 pts)
TEST CASE 1

INPUT
1
srm
University
OUTPUT
Yes
TEST CASE 2

INPUT
2
phackerekarthj
jhakckerearthp
hello
buy
OUTPUT
Yes

#include <iostream>

using namespace std;

int main() {

int n1,n2,mask1,mask2;

string s1,s2;

int T;

cin>>T;

for(int testCase = 1; testCase <= T; testCase++)

cin >> s1 >> s2;

n1 = (int)s1.size(), n2 = (int)s2.size();

mask1 = mask2 = 0;

for ( int i = 0; i < n1; i++ ) mask1 = mask1 | (1<<(s1[i]-'a'));

for ( int i = 0; i < n2; i++ ) mask2 = mask2 | (1<<(s2[i]-'a'));

for ( char p = 'a'; p <= 'z'; p++ ) {

if ( mask1 & (1<<(p-'a')) ) {

if ( mask2 & (1<<(p-'a')) ) {

cout << "Yes" << endl;

goto p1;

cout << "No" << endl;


p1: { }

SESSION: Sum of Subsets


Q. 81: Subset Sum Problem
QUESTION DESCRIPTION

Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum
equal to given sum. Let the sum be 9.
TEST CASE 1

INPUT
5
1 2 3 4 5
OUTPUT
Found a subset with given sum
TEST CASE 2

INPUT
4
10 8 3 4
OUTPUT
No subset with given sum

#include <iostream>

using namespace std;

int main() {

int n;

cin>>n;

int a[n];

int i,x=0;

for(i=0;i<n;i++)

cin>>a[i];
}

int j,k;

for(i=0;i<n;i++)

for(j=0;j<i;j++)

for(k=0;k<j;k++)

if((a[i]+a[j]+a[k])==9)

x=x+1;

break;

if(x>1)

cout<<"Found a subset with given sum";

else

cout<<"No subset with given sum";

return 0;

SESSION: Sum of Subsets


Q. 82: Benny And Subsets
QUESTION DESCRIPTION

This problem is about a little pig named Benny. Benny was given an array of N integers and another separate
integer X.

Benny has to find the number of subsets (not necessarily contiguous) of A such that Bitwise XOR of all
elements contained within the subset evaluates to X.

Probably, you have already guessed that she missed a lot of classes and is not able to solve her homework now.
Therefore, she asks you to help her. Find the number of subsets of A such that Bitwise XOR of all elements of
the subset will be equal to X.

Input format

The first line of the input contains two space separated integers,
N and X.

The next line contains N integers denoting the array A.

Output format

Print in a single line an answer to the problem. As the answer might be large, output it modulo 10^7 + 7.

Constraints

1 <= N <= 10^3


0 <= Ai <= 2^20
TEST CASE 1

INPUT
6 3
1 2 3 0 100500 100500
OUTPUT
8
TEST CASE 2

INPUT
5 3
10 20 1 2 3 0
OUTPUT
2
#include<bits/stdc++.h>

using namespace std;

#define MEM(a, b) memset(a, (b), sizeof(a))

#define FORN(i, n) for(i = 0; i < n; i++)


#define FORAB(i, a, b) for(i = a; i <= b; i++)

#define FORR(i,n) for(i=n-1;i>=0;--i)

#define elif else if

#define mp make_pair

#define pb push_back

#define ff first

#define ss second

#define all(x) (x).begin(),(x).end()

#define rall(x) (x).rbegin(),(x).rend()

#define countset(N) __builtin_popcount(N)

#define MOD 10000007

typedef pair<int,int> PII;

typedef pair<double, double> PDD;

typedef pair<int,long> PIL;

typedef pair<long,long> PLL;

typedef pair<long long,long long> PLLLL;

typedef pair<double,PIL> PDPIL;

typedef vector<int> VI;

typedef vector<long> VL;

typedef vector<double> VD;

typedef vector<long long> VLL;

typedef vector<VI> VVI;

typedef vector<VL> VVL;

typedef vector<VLL> VVLL;

typedef vector<PII > VPII;

typedef vector<PLL > VPLL;

typedef vector<PIL> VPIL;

typedef vector<PLLLL> VPLLLL;

typedef vector<VPLL> VVPLL;


typedef vector<PDPIL> VPDPIL;

#define ll long long

#define l long

#define MIN(a,b) ((a) < (b) ? (a) : (b))

#define MAX(a,b) ((a) > (b) ? (a) : (b))

#define coolreshab ios::sync_with_stdio(false);

#define Pi 3.1415926535897

ll fast_exp(l base,l exp)

if(exp==0)

return 1;

else

if(exp%2==0)

ll temp=fast_exp(base,exp/2);

temp=temp*temp;

if(temp>=MOD)

return temp%MOD;

else

return temp;

else

ll temp=fast_exp(base,(exp-1)/2);

temp=base*temp*temp;

if(temp>=MOD)

return temp%MOD;

else
return temp;

/*freopen("test.txt","r",stdin);

freopen("out.txt","w",stdout);*/

l dp[1005][2048];

VL small,big;

int main()

{ int N,S,i,j,L;

l X,god;

ll ans=0,need;

coolreshab;

cin>>N>>X;

VL arr(N);

FORN(i,N)

cin>>arr[i];

if(arr[i]<=1024)

small.pb(arr[i]);

else

big.pb(arr[i]);
}

dp[0][0]=1;

S=small.size();

FORAB(i,1,S)

FORN(j,2048)

dp[i][j]=dp[i-1][j]+dp[i-1][j^small[i-1]];

if(dp[i][j]>=MOD)

dp[i][j]-=MOD;

L=big.size();

FORN(i,1<<L)

god=0;

FORN(j,L)

if(1<<j&i)

god^=big[j];

need=god^X;

if(need<=2047)

ans+=dp[S][need];

if(ans>=MOD)

ans-=MOD;

}
}

cout<<ans;

return 0;

SESSION: Sum of Subsets


Q. 83: Subset AND
QUESTION DESCRIPTION

You are given a number Z and a set S with N elements. Your job is to find a sub set of S such that the AND of
the given number and this subset is zero. If this sub set is possible print "Yes" otherwise print "No"

Input

First line contains number of test case T. Each test case contains two lines , first line contains two numbers Z
and N , where Z is given number and N is size of set S .

Second line contains N elements of the subset S.

Output

For each test case print Yes if the subset is possible else print No .

Constraints:
1<=T<=100
1<=N<=1000
0<=Ai<=Z<=1000000
TEST CASE 1

INPUT
1
6 2
2 4
OUTPUT
Yes
TEST CASE 2

INPUT
3
10 2
2 0
10 3
1 1 1
5 3
1 5 3
OUTPUT
Yes
Yes
No
#include <bits/stdc++.h>

using namespace std;

vector<int> v;

int main() {

int t, n, z;

scanf("%d", &t);

while (t--) {

v.clear();

scanf("%d %d", &z, &n);

for (int i = 0; i < n; i++) {

int x;

scanf("%d", &x);

v.push_back(x);

bool cond = true;

for (int i = 0; i < 32; i++) {

if ((z & (1 << i))) {

bool okay = false;

for (int j = 0; j < (int)v.size(); j++) {

if ((v[j] & (1 << i)) == 0) okay = true;

if (!okay) cond = false;

if (cond) {

printf("Yes\n");
} else {

printf("No\n");

return 0;

}
SESSION: Sum of Subsets
Q. 84: Possible Permutations
QUESTION DESCRIPTION

Let us have a set of n elements; the objective is to find all the possible permutations of this set. For example if
we have a set of four elements viz. {a, b, c} then we need to print all the permutation of a, b and c as give
below:

1) { a, b, c}
2) { a, c , b}
3) { b, a, c}
4) { b, c, a}
5) { c, a, b}
6) { c, b, a}

Clearly for a set of n elements there exists n! different permutations. One way to generate permutations is to
iterate through n nested loops but that will be hardcoded approach as n may vary from time to time. So one
flexible approach is to generate the permutation recursively. Let us have a set of three elements {a, b, c,} now
to generate permutation follow these steps:

1) Fix a and generate permutation of { b, c }


2) Fix b and generate permutation of { a, c }
3) Fix c and generate permutation of { a, b }
TEST CASE 1

INPUT
2
2
3
OUTPUT
2 3
3 2
TEST CASE 2

INPUT
3
2
6
3
OUTPUT
2 6 3
2 3 6
6 2 3
6 3 2
3 6 2
3 2 6

#include <iostream>

using namespace std;

int n;

void swap(char *x,char*y)

char t;

t=*x;

*x=*y;

*y=t;

void perm(char *a,int l,int r)

if(l==r)

for(int k=0;k<n;k++)

cout<<a[k]<<" ";

cout<<endl;

else

for(int i=l;i<=r;i++)

swap((a+l),(a+i));

perm(a,l+1,r);

swap((a+l),(a+i));
}

int main()

char str[25];

cin>>n;

for(int i=0;i<n;i++)

cin>>str[i];

perm(str,0,n-1);

return 0;

QUESTION
SESSION: Sum of Subsets
Q. 85: Panda and XOR
QUESTION DESCRIPTION

Little Black Panda is mad about XOR operation. Presently he has gone mad and he won't stop performing
XOR operation on various numbers.
Given an array of N numbers, for each subset of the array Little Panda performs MAXOR operation for the
subset. MAXOR operation means that he finds XOR of all elements in that subset (if the subset is [1,2,3] then
MAXOR is 1^2^3=0) .

Little Panda is now exhausted and wants to do something else. Little Panda wants to pick any two subsets the
MAXOR of whose are same.
Little Panda needs to find the number of selections that he can make. He is very very weak in programming so
he wants the answer from you.

Please help little panda in finding out his query.


Since the output can be very large output it modulo 1000000007.

Input Format

The first line contains N i.e. the length of the array.


N lines follow, each containing a non-negative integer.

Output Format
Output Little Panda's Query in a single line.

Constraints
1 <= N <= 100000
0 <= A[i] <= 100
(where A[i] denotes the value of array element)
TEST CASE 1

INPUT
3
1 2 3
OUTPUT
3
TEST CASE 2

INPUT
4
87 96 2 96
OUTPUT
7

#include<cstdio>

#include<iostream>

#include<cstdlib>

#include<cmath>

#include<cstring>

#include<climits>

#include<algorithm>

#include<vector>

#include<set>

#include<map>

#include<bitset>

#include<stack>

#include<queue>

#include<stdio.h>

#include<string.h>

#include<math.h>

#include<functional>
#include<numeric>

using namespace std;

#define FOR(i,a,b) for(i= a ; i < b ; ++i)

#define rep(i,n) FOR(i,0,n)

#define INF INT_MAX

#define ALL(x) x.begin(),x.end()

#define LET(x,a) __typeof(a) x(a)

#define IFOR(i,a,b) for(LET(i,a);i!=(b);++i)

#define EACH(it,v) IFOR(it,v.begin(),v.end())

#define pb push_back

#define sz(x) int(x.size())

#define mp make_pair

#define fill(x,v) memset(x,v,sizeof(x))

#define max(a,b) ((a)>(b)?(a):(b))

#define min(a,b) ((a)<(b)?(a):(b))

#define si(n) scanf("%d",&n)

#define pi(n) printf("%d ",n)

#define pd(n) printf("%lf ",n);

#define pdl(n) printf("%lf\n",n);

#define pin(n) printf("%d\n",n)

#define pln(n) printf("%lld\n",n)

#define pl(n) printf("%lld ",n)

#define sl(n) scanf("%lld",&n)

#define sd(n) scanf("%lf",&n)

#define ss(n) scanf("%s",n)

#define scan(v,n) vector<int> v;rep(i,n){ int j;si(j);v.pb(j);}

#define mod (int)(1e9 + 7)

#define ll long long int

#define F first
#define S second

ll modpow(ll a,ll n,ll temp){ll res=1,y=a;while(n>0){if(n&1)res=(res*y)%temp;y=(y*y)%temp;n/=2;}return


res%temp;}

ll arr[100006],flagit[134],flg[134];

inline ll checkit(ll calc)

if(calc>=mod)

calc%=mod;

return calc;

inline ll chck(ll calc)

while(calc<0)

calc+=mod;

calc%=mod;

return calc;

int main()

ll n,calc,i,j,c1,c2,ans=0;

sl(n);

rep(i,n)

sl(arr[i]);

rep(i,135)

flagit[i]=0;

rep(i,n)

{
rep(j,135)

flg[j]=0;

rep(j,129)

if(flagit[j]!=0)

calc=j^arr[i];

//printf("i=%d j=%d calc=%d\n",i,j,calc);

flg[calc]+=flagit[j];

flg[calc]=checkit(flg[calc]);

rep(j,129)

//printf("i=%d calc=%d calc1=%d\n",i,calc,calc1);

flagit[j]+=flg[j];

flagit[j]=checkit(flagit[j]);

flagit[arr[i]]++;

flagit[arr[i]]=checkit(flagit[arr[i]]);

c2=modpow(2,mod-2,mod);

//pln(c2);

rep(i,129)

//printf("i=%d flagit=%d\n",i,flagit[i]);

calc=flagit[i];

c1=calc*(calc-1);

c1=chck(c1);
c1=c1*c2;

c1=checkit(c1);

ans+=c1;

ans=checkit(ans);

pln(ans);

return 0;

}
SESSION: Sum of Subsets
Q. 87: The Subset Sum
QUESTION DESCRIPTION

The Sum of Subset problem can be gi+E13ve as: Suppose we are given n distinct numbers and we desire to
find all combinations of these numbers whose sums are a given number ( m ).

For example, if n=4 i.e there are four numbers as: 1, 2, 3, 4, 5 and m=5 the all possible subsets are as :
{1,4},{2,3},{5}
TEST CASE 1

INPUT
2
2
6
6
OUTPUT
0 1
TEST CASE 2

INPUT
2
2
6
8
OUTPUT
1 1

#include <iostream>

using namespace std;

long long int mod = 1000000007;

int main()

int T;
cin>>T;

while(T--)

int n,i;

cin>>n;

long long int ans=1,sum=0;

for(i=0;i<n-1;i++){

ans=ans<<1;

ans = (ans % mod);

for(i = 1 ;i <=n;i++) {

sum = ((sum %mod) + ((ans%mod)*(i%mod))%mod)%mod;

cout<<sum<<endl;

return 0;

}
SESSION: Sum of Subsets
Q. 88: Jarvis and Lone Integer
QUESTION DESCRIPTION

Today Tony Stark is upset with Jarvis, as it blew the whole plan of him defeating the Flash in parallel universe
by showing him two images of Flash. Tony couldn't identify the real one and ended up getting hit hard.

Jarvis is upset too and he wants to prove that it was not his mistake. Help Jarvis to prove himself faithful and
true AI.

To prove, that Jarvis is not at fault, he is given N non-negative integers and he has to identify a lone integer
among them. A lone integer is defined as an integer in the given array of integers that is left alone after pairing
each of the other integers.

Two integers can be paired if they have same value in decimal number system and have different indices in the
array. (Look at example case for better understanding and it is guaranteed that there is at most one such
integer.)
NOTE: An integer can't be paired with itself and once paired it can't be used to pair with other integers. (There
are spaces after each input.)

INPUT:
First line will contain T, number of times Jarvis tests itself. For each test there will be two lines. First line of
each test will contain number of integers N he takes, and next line will have N non-negative integers.

OUTPUT:
For each test output one lone integer or -1 if it doesn't exist.

CONSTRAINTS:

1<=T<=500
1<=N<=10^5
1<=Ai<=10^12
TEST CASE 1

INPUT
2
7
8 7 8 1 6 6 7
2
5 5
OUTPUT
1
-1
TEST CASE 2

INPUT
1
4
5 4 1 2
OUTPUT
2

#include <stdio.h>

void solve()

int i, no_of_elements;

long current_number, bitwise_xor_all_numbers = 0, answer;

scanf("%d",&no_of_elements);

for(i = 1; i <= no_of_elements; i++)

{
scanf("%ld",&current_number);

bitwise_xor_all_numbers = bitwise_xor_all_numbers^current_number;

answer = (bitwise_xor_all_numbers > 0 ? bitwise_xor_all_numbers : -1);

printf("%ld\n",answer);

int main()

int no_of_test_cases;

scanf("%d",&no_of_test_cases);

while(no_of_test_cases-- != 0)

solve();

return 0;

QUESTION
SESSION: Sum of Subsets
Q. 89: Xor is Mad
QUESTION DESCRIPTION

The problem is straight and simple.


Given a number X ,find how many positive A ( A>0) exists, such that

1 . A OR X =A + X
2. A<X

Input:
The first line of the input will contain T , the number of test-cases.

Next T lines will contain integer X .

Output:

For each test-case , output the answer in a separate line.

Constraints:

1<=T<=10^5
1<=X<=10^7

Note:
OR is the bitwise Exclusive-OR operator( XOR ). and + is the usual addition symbol
TEST CASE 1

INPUT
4
1
2
3
4
OUTPUT
0
1
0
3
TEST CASE 2

INPUT
10
2
8
8
7
1
7
8
5
7
6
OUTPUT
1
7
7
0
0
0
7
1
0

#include <iostream>
#include <cmath>

using namespace std;

int main()

ios_base::sync_with_stdio(false);

cin.tie(NULL);

unsigned int T,X,ans,i;

cin>>T;

while(T--){

cin>>X;

ans=0;i=0;

if(X%2==0){

ans++;

i++;

X /= 2;

//X>>1L;

while(X){

if(X%2==0){

ans+=pow(2,i);

i++;

X /= 2;//X>>1L;

cout<<ans<<"\n";

return 0;

}
SESSION: Sum of Subsets
Q. 90: Monk's Choice of Numbers
QUESTION DESCRIPTION

The owner of the bakery, Bob, is a clever man. He does not want Monk to finish all his cheesecakes. Hence, he
plays a game.

The Monk is given N numbers and has to select K of these numbers. For each number that Monk chooses, he
will get as many cheesecakes as the number of 1's in the Binary representation of the number i.e. the number of
bits that are set.

Help Monk find the maximum number of cakes that he can have.

Input:

The first line of input contains T. T test cases follow.


First line of each test cases contains 2 space-separated integers N and K.
The next line contains N space-separated integers.

Output:
For each test cases, print the answer in a new line.

Constraints:
1<= T <= 10
1 <= N <= 10^3
0 <= K <= N
0 <= Numbers <= 10^5
TEST CASE 1

INPUT
1
4 2
6 1 2 0
OUTPUT
3
TEST CASE 2

INPUT
2
2 2
1 3
4 2
3 5 1 2
OUTPUT
3
4

#include <iostream>

#include <queue>

using namespace std;


int findones(int n)

int count = 0;

while(n)

if(n&1)

count++;

n>>=1;

return count;

int main()

int t;

cin>>t;

while(t--)

priority_queue<int> pq;

int n,k;

cin>>n>>k;

while(n--)

int x;

cin>>x;

pq.push(findones(x));

int sum = 0;
while(k--)

sum += pq.top();

pq.pop();

cout<<sum<<endl;

return 0;

QUESTION
SESSION: Randomized algorithm
Q. 91: RANDOMIZED ALGORITHMS 4
QUESTION DESCRIPTION

You can win three kinds of basketball points, 1 point, 2 points, and 3 points. Given a total score n, print out all
the combination to compose n.

Examples:
For n = 1, the program should print following:
1

For n = 2, the program should print following:


11
2

For n = 3, the program should print following:


111
12
21
3

For n = 4, the program should print following:


1111
112
121
13
211
22
31

and so on
TEST CASE 1

INPUT
4
OUTPUT
Different compositions formed by 1, 2 and 3 of 4 are
1 1 1 1
1 1 2
1 2 1
1 3
2 1 1
2 2
3 1
TEST CASE 2

INPUT
5
OUTPUT
Different compositions formed by 1, 2 and 3 of 5 are
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2

#include <stdio.h>

void Combi(int n,int i)

static int a[100];

if(n==0)

int j;

for(j=0;j<i;j++)

printf("%d ",a[j]);

printf("\n");

}
else if(n>0)

int k;

for(k=1;k<=3;k++)

a[i]=k;

Combi(n-k,i+1);

int main()

int n;

scanf("%d",&n);

printf("Different compositions formed by 1, 2 and 3 of %d are\n",n);

Combi(n,0);

return 0;

}
SESSION: Randomized algorithm
Q. 92: MINMAX 2
QUESTION DESCRIPTION

Given an array a={3, 20,100, 1, 2}, find the minimum and maximum element.
TEST CASE 1

INPUT
5
3 20 100 1 2
OUTPUT
Minimum : 1
Maximum : 100
TEST CASE 2

INPUT
7
3 6 18 39 85 100 120
OUTPUT
Minimum : 3
Maximum : 120
Problem with Question? Report

#include <iostream>

using namespace std;

int main()

int n,a[10],i,mx,mi;

cin>>n;

for(i=0;i<n;i++)

cin>>a[i];

mx=a[0];

for(i=0;i<n;i++)

if(a[i]>mx)

{ mx=a[i];}

mi=a[0];

for(i=0;i<n;i++)

if(a[i]<mi)

{ mi=a[i];}

cout<<"Minimum : "<<mi<<endl;

cout<<"Maximum : "<<mx;
return 0;

Q. 94: MINMAX 1
QUESTION DESCRIPTION

Given a list of N integers, your task is to select K integers from the list such that its unfairness is minimized.
if (x1,x2,x3,,xk) are K numbers selected from the list N, the unfairness is defined as max(x1,x2,,xk)-
min(x1,x2,,xk)
where max denotes the largest integer among the elements of K, and min denotes the smallest integer among
the elements of K.

Input Format
The first line contains an integer N.
The second line contains an integer K.
N lines follow. Each line contains an integer that belongs to the list N.

Note: Integers in the list N may not be unique.

Output Format
An integer that denotes the minimum possible value of unfairness.

Constraints
2<=N<=10^5
2<=K<=N
0=<integer in N <=10^9
TEST CASE 1

INPUT
3
2
21
66
11
OUTPUT
10
TEST CASE 2

INPUT
5
3
14
75
44
99
22
OUTPUT
30

#include <iostream>
#include<cstdio>

#include<vector>

#include<algorithm>

#include<climits>

using namespace std;

int main()

int n,K,uf=INT_MAX;

int j,k;

cin>>n>>K;

int list[n];

for(int i=0;i<n;i++)

cin>>list[i];

sort(list,list+n);

for(j=0,k=K-1;k<n;j++,k++)

if(uf>(list[k]-list[j]))

uf=list[k]-list[j];

cout<<uf;

return 0;

SESSION: Randomized algorithm


Q. 95: RANDOMIZED ALGORITHMS 8
QUESTION DESCRIPTION

Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic
operators (+, ++, , -, .. etc).

Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by
performing AND (&) of two bits.
Above is simple Half Adder logic that can be used to add 2 single bits.
We can extend this logic for integers. If x and y dont have set bits at same position(s), then bitwise XOR (^) of
x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND
of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
TEST CASE 1

INPUT
5 6
OUTPUT
11
TEST CASE 2

INPUT
12 13
OUTPUT
25

#include <iostream>

using namespace std;

int add(int x,int y)

if(y==0)

return x;

else

return (add((x^y),(x&y)<<1));

int main()

{ int x,y;

cin>>x>>y;

cout<<add(x,y);

return 0;

}
Q. 96: RANDOMIZED ALGORITHMS 1
QUESTION DESCRIPTION

Given two signed integers, write a function that returns true if the signs of given integers are different,
otherwise false. For example, the function should return true -1 and +100, and should return false for -100 and
-200. The function should not use any of the arithmetic operators.

Let the given integers be x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR
of x and y will have the sign bit as 1 iff they have opposite sign. In other words, XOR of x and y will be
negative number number iff x and y have opposite signs
TEST CASE 1

INPUT
100
-120
OUTPUT
Signs are opposite
TEST CASE 2

INPUT
134
564
OUTPUT
Signs are not opposite

#include <iostream>

using namespace std;

int sign(int x,int y)

return(x^y)<0;

int main()

int x,y;

cin>>x>>y;

if(sign(x,y)==1)

cout<<"Signs are opposite";

else cout<<"Signs are not opposite";

return 0;

SESSION: Randomized algorithm


Q. 97: RANDOMIZED ALGORITHMS 5
QUESTION DESCRIPTION

Given a number x, find next number with same number of 1 bits in its binary representation.

For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit
machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).
TEST CASE 1

INPUT
150
OUTPUT
153
TEST CASE 2

INPUT
170
OUTPUT
172

#include <iostream>

using namespace std;

typedef unsigned int uint_t;

uint_t snoob(uint_t x)

uint_t rightOne;

uint_t nextHigherOneBit;

uint_t rightOnesPattern;

uint_t next=0;

if(x)

rightOne= x & -(signed)x;

nextHigherOneBit = x + rightOne;

rightOnesPattern = x ^ nextHigherOneBit;

rightOnesPattern = (rightOnesPattern)/rightOne;

rightOnesPattern >>=2;

next = nextHigherOneBit | rightOnesPattern;

}
return next;

int main()

int x;

cin>>x;

cout<<snoob(x);

getchar();

return 0;

SESSION: Randomized algorithm


Q. 98: RANDOMIZED ALGORITHMS 3
QUESTION DESCRIPTION

A permutation, also called an arrangement number or order, is a rearrangement of the elements of an ordered
list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.


ABC ACB BAC BCA CBA CAB
TEST CASE 1

INPUT
ABC
OUTPUT

ABC
ACB
BAC
BCA
CBA
CAB
TEST CASE 2

INPUT
CDE
OUTPUT
CDE
CED
DCE
DEC
EDC
ECD

#include <iostream>

#include<string.h>

using namespace std;

void swap(char *x,char *y)

char t;

t=*x;

*x=*y;

*y=t;

void per(char *a,int l,int r)

int i;

if(l==r)

cout<<a<<endl;

else

for(i=l;i<=r;i++)

swap((a+l),(a+i));

per(a,l+1,r);

swap((a+l),(a+i));

int main()

{
char str[10];

int n;

cin>>str;

n=strlen(str);

per(str,0,n-1);

return 0;

SESSION: Randomized algorithm


Q. 99: RANDOMIZED ALGORITHMS 7
QUESTION DESCRIPTION

Given a integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed
to use %, /, *.

Examples:
Input: 2
Output: 7

Input: 5
Output: 17 (Ignore the digits after decimal point)

Solution:
1. We can get x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to calculate x/2, right shift
x by 2.
TEST CASE 1

INPUT
6
OUTPUT
21
TEST CASE 2

INPUT
7
OUTPUT
24

#include <iostream>

#include<math.h>

using namespace std;

int main()
{

int z,x,y;

cin>>x;

y=x>>1;

z=x<<1;

x=x+y+z;

cout<<x;

return 0;

Q. 100: RANDOMIZED ALGORITHMS 2


QUESTION DESCRIPTION

Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to
n.
TEST CASE 1

INPUT
8
OUTPUT
Total set bit count is 13
TEST CASE 2

INPUT
12
OUTPUT
Total set bit count is 22

#include <iostream>

using namespace std;

unsigned int cntSet(unsigned int n)

unsigned int cnt=0;

while(n)

cnt+=(n&1);
n>>=1;

return cnt;

int main()

unsigned int n;

unsigned int i,tt=0;

cin>>n;

for(i=1;i<=n;i++)

tt+=cntSet(i);

cout<<"Total set bit count is "<<tt;

return 0;

You might also like