Samsung

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

# Samsung Problems for R&D India

### MUST DO PROBLEMS FOR ONLINE 3-HOUR TEST


* Bipatite Graph
* Detect and Print Cycle in Graph
* Burst Balloon
* Endoscopy
* Mr Lee
* Mr Kim
* Research Team / Rare Elements
* Spaceship / Bomb Explosion
* Wormhole
* Omnious Number

Q1. 2D MATRIX
#include <bits/stdc++.h>
#include <iostream>
using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int n;
bool isNoPath = false;
cin>>n;
char arr[n][n];
pair<int,int> dp[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
dp[i][j].first = 0;
dp[i][j].second = 0;
}
}
arr[0][0]='0';
arr[n-1][n-1]='0';

//Move to last coulumn


for(int i=n-2;i>=0;i--)
{
if(arr[i][n-1]=='x')
{
for(int j=i;j>=0;j--)
{
dp[j][n-1].first = dp[j][n-1].second = INT_MIN;
}
break;
}
else
{
dp[i][n-1].first = dp[i+1][n-1].first+(arr[i][n-1]-48);
dp[i][n-1].second = 1;
}
}
//Move to last row
for(int i=n-2;i>=0;i--)
{
if(arr[n-1][i]=='x')
{
for(int j=i;j>=0;j--)
{
dp[n-1][j].first = dp[n-1][j].second = INT_MIN;
}
break;
}
else
{
dp[n-1][i].first = dp[n-1][i+1].first+(arr[n-1][i]-48);
dp[n-1][i].second = 1;
}
}

//Move to Remaining matrix


for(int i=n-2;i>=0;i--)
{
for(int j=n-2;j>=0;j--)
{
if(arr[i][j]=='x')
{
dp[i][j].first = dp[i][j].second = INT_MIN;
}
else
{
int maxi = max(dp[i][j+1].first,max(dp[i+1][j+1].first,dp[i+1][j].first));
int path = 0;
if(dp[i][j+1].first==maxi)
path += dp[i][j+1].second;
if(dp[i+1][j+1].first==maxi)
path += dp[i+1][j+1].second;
if(dp[i+1][j].first==maxi)
path += dp[i+1][j].second;
if(maxi==INT_MIN)
{
isNoPath = true;
break;
}
dp[i][j].first = maxi+(arr[i][j]-48);
dp[i][j].second = path;
}
}
}
if(isNoPath)
cout<<"0"<<" "<<"0"<<endl;
else
cout<<dp[0][0].first<<" "<<dp[0][0].second<<endl;
}
return 0;
}

Q2. AGGRESSIVE COW


/*
You are given an array of integers which represents positions available and an integer c(cows).
Now you have to choose c positions such that minimum difference between cows is maximized.
For example,
1 3 5 8 10
c=3

Output: 4
1 5 10
*/

#include<bits/stdc++.h>
using namespace std;

bool Comperator(int x,int a[],int n,int k){// We want to know if we can get at least x distance with k cows
int currentCows = 1;
int leftmost = 0;

for(int i=1;i<n;++i){
if(a[i] - a[leftmost] >= x){
leftmost = i;
++currentCows;
if(currentCows == k)
return 1;
}
}
return 0;
}

int main()
{
int t; cin >> t;
for(int i=0;i<t;++i){
int n,k;cin >> n >> k;
int a[100000];
for(int j=0;j<n;++j){
cin >> a[j];
}
sort(a,a+n);

int l = 0;
int r = a[n-1] - a[0] + 1;
// If we can do with x distance then obviosult we can do it with <=x.
// So We need to update it
//True True True True True True True . .. . . False False False ==> We want to find the last true

while(r - l > 0){


int m = (l + r + 1) /2;

if(Comperator(m,a,n,k)==true){
l = m; // l is true now
}
else
r = m-1; // R is false now
}

cout << l << '\n';


}
}

Q3. BIPARTITE VERTICES


/*
Given a graph print either of the set of the vertices that are colored with the same color. And if the graph
is not bipartite print “-1”. Test cases also included the cases when a graph is not connected.
*/

#include<iostream>
using namespace std;
int n;
int arr[100][100]={0};

bool isBiPartite(int i,int color[]){


bool flag = true;
for(int j=0;j<n;j++){
if(arr[i][j] == 1){
if(color[j] == -1){//If color of current node not set
color[j] = 1 - color[i];//Set color opposite to adjacent node
flag = flag & isBiPartite(j,color);//Check for adjacent node
}
else if(color[i] == color[j]){//If color is same for adjacent node return false
return false;
}
}
}
return flag;
}

int main(){
cin >> n;//No of nodes in graph
int color[n];//For coloring of graph
for(int i=0;i<n;i++){
color[i] = -1;
for(int j=0;j<n;j++){
cin >> arr[i][j];//Input graph adjacency matrix
}
}

for(int i=0;i<n;i++){
if(color[i]==-1){
color[i] = 0;//Color starting node(of connected/disconnected graph) as 0
if(!isBiPartite(i,color)){//If not bipartite then print -1
cout << "-1" << endl;
return 0;
}
}
}

for(int i=0;i<n;i++){
if(color[i] == 0){
cout << i << " ";//Print all nodes with color 0
}
}

return 0;
}

Q4. BURST BALLOON -1


/*
There are n balloons and n bullets and each balloon is assigned with a particular number (point).
Whenever a particular balloon is shot the no of points increases by
1.the multiplication of point assigned to balloon on left and that of right side.
2.point assigned to left if no right exists
3.point assigned to right if no left exists.
4.the point assigned to itself if no other balloon exists.

You have to output the maximum no of points possible.

Input
1234

Output
20
*/

#include <iostream>
using namespace std;

int maxcoins(int A[],int siz)


{
int nums[siz+2];
int n=1;
for(int i=0;i<siz;i++)
{
if(A[i]>0)
{
nums[n] = A[i];
n++;
}
}
nums[0] = nums[n] = 1;
n++;

int dp[n][n] = {};

for(int j=2;j<n;j++)
{
for(int left=0;left<n-j;left++)
{
int right = left+j;
for(int i = left+1;i<right;i++)
{
if(left==0 && right==n-1)
dp[left][right] = max(nums[left]*nums[i]*nums[right] + dp[left][i] + dp[i][right],dp[left][right]);
else
dp[left][right] = max(nums[left]*nums[right] + dp[left][i] + dp[i][right],dp[left][right]);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
}
return dp[0][n-1];
}

int main()
{
int siz;
cin >> siz;
int A[siz];
for(int i=0;i<siz;i++)
cin >> A[i];

int ans = maxcoins(A,siz);


cout << ans << endl;
return 0;
}

/*
5
12354
*/

Q5. BURST BALLOON - 2


Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums.
You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.
Input: [3,1,5,8]
Output: 167
*/

int maxCoins(vector<int>& nums) {


/* O(n^3) Time and O(n^2) Space */
int size = nums.size();
if(size == 0)
return 0;

int i, j, k;
vector< vector<int> > dp(size, vector<int>(size, 0));

for(int len = 1; len <= size; len++){


for(i = 0; i <= size - len; i++){
j = len + i - 1;
for(k = i; k <= j; k++){
/* Left/Right Value has default 1 but holds prev and after ballon value if k is in middle */
int leftValue = 1;
int rightValue = 1;

if(i != 0)
leftValue = nums[i-1];
if(j != size-1)
rightValue = nums[j+1];

/* Before and After - current k balloon is last to burst select the left side and right side to burst */
int before = 0;
int after = 0;

if(i != k)
before = dp[i][k-1];
if(j != k)
after = dp[k+1][j];

dp[i][j] = max(dp[i][j],
leftValue * nums[k] * rightValue + before + after);
}
}
}
return dp[0][size-1];
}

Q6. CHESS PIECE:


There is a mobile piece and a stationary piece on the N×M chessboard.
The available moves of the mobile piece are the same as set out in the image below.
You need to capture the stationary piece by moving the mobile piece with the minimum amount of moves.

Write a program to find out the minimum number moves to catch a piece.

[Input]
Several test cases can be included in the inputs. T, the number of cases is given in the first row of the
inputs. After that, the test cases as many as T (T ≤ 20) are given in a row.
N, the numbers of the rows and M, the number of columns of the chessboard are given in the first row of
each test case.
R & C is the location information of the attacking piece and S & K is the location of the defending pieces
and are given in the row at the second line. However, the location of the uppermost end of the left end
is (1, 1)

[Output]
For each test case, you should print "Case #T" in the first line where T means the case number.

For each test case, you should output the minimum number of movements to catch a defending piece at the
first line of each test case. If not moveable, output equals ‘-1’.

[I/O Example]

Input
2
99
3528
20 20
2379

Output
Case #1
2
Case #2
5
*/

#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
typedef struct
{
int x;
int y;
int level;
}data;
int mv[8][2] = {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};

int main(){
int T;
cin>>T;
for(int t=1; t<=T; t++)
{
int n,m,r1,c1,r2,c2;
cin>>n>>m;
int a[n+1][m+1];
memset(a,0,sizeof(int)*(n+1)*(m+1));
cin>>r1>>c1>>r2>>c2;
data d,d1,d2;
queue<data> qt;
d.x = r1;
d.y = c1;
d.level = 0;
qt.push(d);
a[d.x][d.y] = 2;
int tmx,tmy,tml;
int steps = 0;
bool f = false;
while(!qt.empty())
{
if(f)
{
break;
}
d1 = qt.front();
qt.pop();
for(int k=0; k<8; k++)
{
tmx = d1.x + mv[k][0];
tmy = d1.y + mv[k][1];
tml = d1.level + 1;

if(tmx>=1 && tmx<=n && tmy>=1 && tmy<=m && a[tmx][tmy] == 0)


{
if(tmx == r2 && tmy == c2)
{
steps = tml;
f = true;
break;
}
d2.x = tmx;
d2.y = tmy;
d2.level = tml;
qt.push(d2);
a[d2.x][d2.y] = 2;
}
}
}
if(!f)
{
steps = -1;
}
cout<<"Case #"<<t<<endl;
cout<<steps<<endl;
}
//cout << "Hello world!" << endl;
return 0;
}

Q7. CONVEX HAUL:


/*
Given random points in a 2-D plane, construct a convex polygon with minimum area of covering and
which encompasses all the given points.
*/
#include<bits/stdc++.h>
int cou = 0;

struct Point{
int x, y;
};

int orientation(Point p, Point q, Point r){


int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);

if (val == 0) return 0;
return (val > 0)? 1: 2;
}

bool cmp(Point &a, Point &b){


if(a.x==b.x&&a.y==b.y)
cou++;

if(a.x == b.x)
return a.y < b.y;
else
return a.x < b.x;
}

bool myFunc(Point &a, Point &b){


return (a.x==b.x && a.y==b.y);
}

void convexHull(Point *points, int n){


cou = 0;
if (n < 3){
cout << "-1";
return;
}

vector<Point> hull;

int l = 0;
for (int i = 1; i < n; i++)
if (points[i].x < points[l].x)
l = i;

int p = l, q;
do{
hull.push_back(points[p]);

q = (p+1)%n;

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


{
if (orientation(points[p], points[i], points[q]) == 2)
q = i;
}
p = q;

} while (p != l);

sort(hull.begin(), hull.end(), cmp);

auto ip = unique(hull.begin(), hull.end(), myFunc);

hull.resize(std::distance(hull.begin(), ip));

if(n < 4 && cou > 0 || hull.size() < 3){


cout << "-1";
return;
}
else{
for (int i = 0; i < hull.size(); i++){
if(i != hull.size() - 1)
cout << hull[i].x << " " << hull[i].y << ", ";
else
cout << hull[i].x << " " << hull[i].y;
}
}
}

int main(){
int t, n;
cin >> t;
while(t--){
cin >> n;
Point *points = new Point[n];

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


cin >> points[i].x >> points[i].y;
}

convexHull(points, n);
cout << "\n";
}
return 0;
}

Q8. CROW POT:

/*
There are N pots. Every pots has some water in it. They may be partially filled.
Every pot is associated with overflow number O which tell how many minimum no. of stones required
for that pot to overflow. The crow know O1 to On(overflow no. for all the pots). Crow wants some K
pots to be overflow. So the task is minimum number of stones he can make K pots overflow in worst case.

Array of overflow no--. {1,...,On}


Number of pots--n
No of pots to overflow-- k

Let say two pots are there with overflow no.s {5,58}, and crow has to overflow one pot(k=1).
So crow will put 5 stones in pot with overflow no.(58), it will not overflow, then he will put in
pot with overflow no.(5), hence the total no. of stones to make overflow one pot is=10.
*/
#include<iostream>
#include<algorithm>
using namespace std;

int n, k;

void merger(int *overflow_numbers, int l, int m, int r){


int i,j,k;
int n1=m-l+1;
int n2=r-m;
int L[n1], R[n2];
for(int i=0; i<n1; i++){
L[i]=overflow_numbers[l+i];
}
for(int j=0; j<n2; j++){
R[j]=overflow_numbers[m+1+j];
}

i=0;
j=0;
k=l;
while(i<n1 && j<n2){
if(L[i]<=R[j]){
overflow_numbers[k]=L[i];
i++;
}else{
overflow_numbers[k]=R[j];
j++;
}
k++;
}
while(i<n1){
overflow_numbers[k]=L[i];
k++;
i++;
}
while(j<n2){
overflow_numbers[k]=R[j];
k++;
j++;
}
}

void merge_sort(int *overflow, int l, int r){


if(l<r){
int m=l+(r-l)/2;
merge_sort(overflow, l, m);
merge_sort(overflow, m+1, r);
merger(overflow, l, m, r);
}
}

int minCrowPotStoneSameer(int *arr){


int stone = 0, index = 0, left = n, prev = 0;

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


stone += left * (arr[index] - prev);
left--;
prev += arr[index]-prev;
index++;
}

return stone;
}

int minCrowPotStoneFirst(int *overflow){


int result = 0;
for(int i=0 ; i<k ;i++){
int min = overflow[i];
for(int j=i; j<n; j++){
overflow[j] = overflow[j] - min;
result = result + min;
}
}
return result;
}

int minCrowPotStoneSecond(int *overflow_numbers){


int total_stones=0;
for(int i=n-1; i>0; i--){
overflow_numbers[i] = max(0,overflow_numbers[i]-overflow_numbers[i-1]);
}

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


total_stones+=(overflow_numbers[i]*(n-i));
}
return total_stones;
}

int main(){
cin >> n;
int *arr = new int[n + 1];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cin >> k;

merge_sort(arr, 0, n-1);

cout << minCrowPotStoneSecond(arr);


return 0;
}

/*
#include<bits/stdc++.h>
using namespace std;
long long dp[1005][1005];

long long solve(int arr[], int n, int p)


{
long long ans = INT_MAX;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=p;j++)
{
dp[i][j] = INT_MAX;
}
}
for(int i=n;i>0;i--)
{
for(int z=1; z<=p;z++)
{
if(z==1)
{
dp[i][z] = (n-i+1)*arr[i];
continue;
}
for(int k = i+1;k<=n;k++)
{
dp[i][z] = min(dp[i][z], dp[k][z-1] + arr[i]*(k-i));
}
}
}
for(int i=1;i<=n;i++)
{
ans = min(ans, dp[i][p]);
}
return ans;
}

int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int k;
cin>>k;
int over[n+1];
for(int i=1;i<=n;i++)
{
cin>>over[i];
}
sort(over+1, over+n+1);
cout << solve(over, n, k)<<endl;
}
return 0;
}
*/

Q9: DIRECTED GRAPH CYCLE PRINT


#include<iostream>
using namespace std;

int graph[100][100];
int n;

bool dfs( int node , bool *visited , bool *inloop , int &prev ){
visited[node] = 1;
inloop[node] = 1;
for(int i=0;i<n;i++){
if( graph[node][i]){
if(!visited[i]){
if(dfs( i , visited , inloop , prev)){

if(i==prev)
cout<<i<<" " , prev=-1;
else if (prev!=-1)
cout<<i<<" ";

return true;
}
}
else if ( inloop[i] ){
prev=i;
return true;
}
}
}

inloop[node]=0;
return false;
}

bool checkCycle (bool *visited){


int prev = -1;
bool inloop[n] = {false};

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


if( !visited[i] && dfs(i,visited, inloop, prev))
return true;

return false;
}

int main(){
// Input nodes
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
graph[i][j]=0;

// Input Edges
int t;
cin>>t;
int x,y;
for(int i=0;i<t;i++){
cin>>x>>y;
graph[x][y]=1;
}

bool visited[n] = {false};

cout<<checkCycle(visited)<<endl;

return 0;
}

Q10. UNDIRECTED GRAPH PRINT CYCLE:

#include <iostream>
using namespace std;

int a[100][100], n;

bool findcycle(int st, bool visited[], int parent, int &prev){


visited[st]=true;
for(int j=0;j<n;j++){

if(a[st][j] == 1 && visited[j] == false){

if( findcycle(j, visited, st, prev) ){


if(st==prev){
cout << st << " ";
prev = -1;
}
else if(prev != -1){
cout << st << " ";
}

return true;
}

}
else if(a[st][j] == 1 && parent != j && visited[j] == true){
cout << st << " ";
prev = j;
return true;
}

}
return false;
}

int main(){
memset(a,0,sizeof(a));
int m;
cin >> n >> m;

int x,y;
while(m--){
cin>>x>>y;
a[x][y]=1;
a[y][x]=1;
}

bool visited[n] = {false};


int parent = -1, prev = -1;
findcycle(0,visited,parent,prev);

return 0;
}

Q11. DOCTOR PROBABLITY:


A Doctor travels from a division to other division where divisions are connected like a graph(directed graph) and
the edge weights are the probabilities of the doctor going from that division to other connected division but the
doctor stays 10mins at each division now there will be given time and had to find the division in which he will be
staying by that time and is determined by finding division which has high probability.
Input is number of test cases followed by the number of nodes, edges, time after which we need to find the division
in which he will be there, the edges starting point, end point, probability.

Note: If he reaches a point where there are no further nodes then he leaves the lab after 10 mins and the traveling
time is not considered and during that 10min at 10th min he will be in next division, so be careful

2
6 10 40
1 2 0.3 1 3 0.7 3 3 0.2 3 4 0.8 2 4 1 4 5 0.9 4 4 0.1 5 6 1.0 6 3 0.5 6 6 0.5
6 10 10
1 2 0.3 1 3 0.7 3 3 0.2 3 4 0.8 2 4 1 4 5 0.9 4 4 0.1 5 6 1.0 6 3 0.5 6 6 0.5

6 0.774000
3 0.700000
*/

#include<iostream>
using namespace std;

void docProb(double **graph, int nodes, int time, int curNode, double p, double *answer){
if(time <= 0){
answer[curNode] += p;
return;
}

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


if(graph[curNode][i] != 0){
p *= graph[curNode][i];
docProb(graph, nodes, time - 10, i, p, answer);
p /= graph[curNode][i];
}
}

int main(){
int t;
cin >> t;
while(t--){
int nodes, edges, time;
cin >> nodes >> edges >> time;

double **arr = new double*[nodes];


for(int i=1; i<=nodes; i++){
arr[i] = new double[nodes];
for(int j=1; j<=nodes; j++){
arr[i][j] = 0;
}
}

int from, to;


double prob;
for(int i=0; i<edges; i++){
cin >> from >> to >> prob;
arr[from][to] = prob;
}

/* Initalise answer and function call */


double answer[nodes] = {0.0};
docProb(arr, nodes, time, 1, 1.0, answer);

/* Select max Probability node */


double finalProb = 0.0;
int finalDivison = 0;

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


if(answer[i] > finalProb){
finalProb = answer[i];
finalDivison = i;
}
}
cout << finalDivison << " " << finalProb << "\n";
}
return 0;
}

Q12. ENDOSCOPY
#include<iostream>
using namespace std;

struct Node{
bool left, right, up, down;
};

struct Point{
int x, y;
};

int n, m, sX, sY, len;


int arr[1005][1005];
int vis[1005][1005], dis[1005][1005];

int result;
Node pipes[1005][1005];
Point queue[1000005];

bool isValid(int i, int j){


return (i>=0 && i<n && j>=0 && j<m);
}

void bfs(){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
vis[i][j] = 0;
dis[i][j] = 0;
}
}

int front = 0, rear = 0;

dis[sX][sY] = 1;
vis[sX][sY] = 1;

if( arr[sX][sY] == 0 ){
result = 0;
return;
}

queue[rear].x = sX;
queue[rear].y = sY;
rear = (rear + 1) % 1000005;

while(front != rear){
int p = queue[front].x;
int q = queue[front].y;
front = (front + 1) % 1000005;

if( 1 + dis[p][q] <= len ){

/* Row Up */
if( isValid(p-1, q) && vis[p-1][q] == 0 && pipes[p-1][q].down && pipes[p][q].up ){
vis[p-1][q] = 1;
dis[p-1][q] = 1 + dis[p][q];
result++;

queue[rear].x = p-1;
queue[rear].y = q;
rear = (rear + 1) % 1000005;
}

/* Row Down */
if( isValid(p+1, q) && vis[p+1][q] == 0 && pipes[p+1][q].up && pipes[p][q].down ){
vis[p+1][q] = 1;
dis[p+1][q] = 1 + dis[p][q];
result++;

queue[rear].x = p+1;
queue[rear].y = q;
rear = (rear + 1) % 1000005;
}

/* Column Left */
if( isValid(p, q-1) && vis[p][q-1] == 0 && pipes[p][q-1].right && pipes[p][q].left ){
vis[p][q-1] = 1;
dis[p][q-1] = 1 + dis[p][q];
result++;
queue[rear].x = p;
queue[rear].y = q-1;
rear = (rear + 1) % 1000005;
}

/* Column Right */
if( isValid(p, q+1) && vis[p][q+1] == 0 && pipes[p][q+1].left && pipes[p][q].right ){
vis[p][q+1] = 1;
dis[p][q+1] = 1 + dis[p][q];
result++;

queue[rear].x = p;
queue[rear].y = q+1;
rear = (rear + 1) % 1000005;
}

}
}
}

int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//code
int t;
cin >> t;
while(t--){
result = 1;
cin >> n >> m >> sX >> sY >> len;

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


for(int j=0; j<m; j++){
cin >> arr[i][j];

if( arr[i][j] == 1 ){
pipes[i][j].left = true;
pipes[i][j].right = true;
pipes[i][j].up = true;
pipes[i][j].down = true;
}
else if( arr[i][j] == 2 ){
pipes[i][j].left = false;
pipes[i][j].right = false;
pipes[i][j].up = true;
pipes[i][j].down = true;
}
else if( arr[i][j] == 3 ){
pipes[i][j].left = true;
pipes[i][j].right = true;
pipes[i][j].up = false;
pipes[i][j].down = false;
}
else if( arr[i][j] == 4 ){
pipes[i][j].left = false;
pipes[i][j].right = true;
pipes[i][j].up = true;
pipes[i][j].down = false;
}
else if( arr[i][j] == 5 ){
pipes[i][j].left = false;
pipes[i][j].right = true;
pipes[i][j].up = false;
pipes[i][j].down = true;
}
else if( arr[i][j] == 6 ){
pipes[i][j].left = true;
pipes[i][j].right = false;
pipes[i][j].up = false;
pipes[i][j].down = true;
}
else if( arr[i][j] == 7 ){
pipes[i][j].left = true;
pipes[i][j].right = false;
pipes[i][j].up = true;
pipes[i][j].down = false;
}
else{
pipes[i][j].left = false;
pipes[i][j].right = false;
pipes[i][j].up = false;
pipes[i][j].down = false;
}

}
}

bfs();
cout << result << "\n";
}
return 0;
}

Q13. FSIHERMAN
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#define MAX 3

int fishspot[100]; // fishing spots


int gate[MAX]; // position of gates
int fishermen[MAX]; // no of fishermen at each gate
int N; // total no of fishing spots
int visited[MAX]; // occupied fishing spots
int Answer; // result

// To unmark spots occupied by fishermen of gate# index


class GFG
{
public :
void reset_fishspot(int index)
{
int i;
for (i = 1; i <= N; i++)
if (fishspot[i] == index + 1)
fishspot[i] = 0;
}

// Calculate minimum distance while


// allotting spots to fishermen of gate# index.
// Returns number of positions possible
// with minimum disance.
// pos1, pos2 is used to return positions
int calculate_distance(int index, int*pos1,
int *pos2, int *score)
{
int i, sum = 0, left_min = 999999,
right_min = 999999,
left, right, npos = 0;
*pos1 = *pos2 = *score = 0;

left = right = gate[index];

// Allot spots to all fishermen except


// last based on minimum distance
for (i = 1; i < fishermen[index]; i++)
{
if (fishspot[gate[index]] == 0)
{
sum++;
fishspot[gate[index]] = index + 1;
}
else
{
left_min = right_min = 999999;

while ((left > 0) && (fishspot[left] > 0))


left--;

while ((right <= N) &&


(fishspot[right] > 0))
right++;

if ((left > 0) && (fishspot[left] == 0))


left_min = gate[index] - left + 1;

if ((right <= N) && (fishspot[right] == 0))


right_min = right - gate[index] + 1;

if (right_min == left_min)
{
// Place 2 fishermen, if avaiable
if ((fishermen[index] - i - 1) > 1)
{
fishspot[left] = fishspot[right] = index + 1;
sum += (2 * left_min);
i++;

// If all fishermen are alloted spots


if (i == fishermen[index])
{
npos = 1;
*score = sum;
return npos;
}
}
else
{
sum += left_min;
fishspot[left] = index + 1;
}
}
else if (left_min < right_min)
{
sum += left_min;
fishspot[left] = index + 1;
}
else if (right_min < left_min)
{
sum += right_min;
fishspot[right] = index + 1;
}
}
}

left_min = right_min = 99999;

// Allot spot to last fishermen


while ((left > 0) && (fishspot[left] > 0))
left--;

if ((left > 0) && (fishspot[left] == 0))


left_min = gate[index] - left + 1;

while ((right <= N) && (fishspot[right] > 0))


right++;

if ((right <= N) && (fishspot[right] == 0))


right_min = right - gate[index] + 1;

if ((sum + left_min) == (sum + right_min))


{
npos = 2;
*pos1 = left;
*pos2 = right;
*score = sum + left_min;
}
else if ((sum + left_min) >
(sum + right_min))
{
npos = 1;
*score = sum + right_min;
fishspot[right] = index + 1;
}
else if ((sum + left_min) <
(sum + right_min))
{
npos = 1;
*score = sum + left_min;
fishspot[left] = index + 1;
}
return npos;
}

// Solve is used to select next gate


// and generate all combinations.
void solve(int index, int sum, int count)
{
int npos, pos1, pos2, score, i;

visited[index] = 1;

if (sum > Answer)


return;

npos = calculate_distance(index, &pos1,


&pos2, &score);
sum += score;

if (count == MAX)
{
if (Answer > sum)
Answer = sum;

return;
}

if (npos == 1)
{
for (i = 0; i < MAX; i++)
{
if (visited[i] == 0)
{
solve(i, sum, count + 1);
visited[i] = 0;
reset_fishspot(i);
}
}
}
else if (npos == 2)
{
fishspot[pos1] = index + 1;
for (i = 0; i < MAX; i++)
{
if (visited[i] == 0)
{
solve(i, sum, count + 1);
visited[i] = 0;
reset_fishspot(i);
}
}

fishspot[pos1] = 0;
fishspot[pos2] = index + 1;
for (i = 0; i < MAX; i++)
{
if (visited[i] == 0)
{
solve(i, sum, count + 1);
visited[i] = 0;
reset_fishspot(i);
}
}
fishspot[pos2] = 0;
}
}
};

// Driver Code
int main()
{
GFG g;

int i;
/*scanf("%d", &N); // for input

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


{
scanf("%d %d", &gate[i], &fishermen[i]);
visited[i] = 0;
}*/

N = 10; // total no of fishing spots

// position of gates(1-based indexing)


gate[0] = 4;
gate[1] = 6;
gate[2] = 10;

//no of fishermen at each gate


fishermen[0] = 5; //gate1
fishermen[1] = 2; //gate 2
fishermen[2] = 2; //gate 3

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


fishspot[i] = 0;

Answer = 999999;

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


{
g.solve(i, 0, 1);
visited[i] = 0;
g.reset_fishspot(i);
}

cout << Answer << endl;

return 0;
}
// This code is contributed by SoM15242

Q14. FROG JUMP:


http://ideone.com/oXdBaF

Given a 2 D matrix where 1 represent the places where the frog can jump and 0 represent the empty spaces,
the frog can move freely in horizontal direction (on 1’s only) without incurring any cost (jump).
A vertical jump from a given point of the matrix to other point on the matrix can be taken (on 1’s only)
with cost as the number of jumps taken.
Given a source and destination, the frog has to reach the destination minimizing the cost (jump).
*/

#include <iostream>
using namespace std;
#define QS 1000005

struct Point{
int x, y;
};

int n, sX, sY, tX, tY;


int mat[105][105], dis[105][105], vis[105][105];

Point queue[QS];
int front = 0, rear = 0;

int dirX[] = {1,0,-1,0};


int dirY[] = {0,1,0,-1};

bool isValid(int i, int j){


return (i>=0 && i<n && j>=0 && j<n);
}

void calculateFrogJump(){
queue[rear].x = sX;
queue[rear].y = sY;
rear = (rear + 1) % QS;

vis[sX][sY] = 1;
dis[sX][sY] = 0;

while(front != rear){
int p = queue[front].x;
int q = queue[front].y;
front = (front + 1) % QS;

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


int newX = p + dirX[i];
int newY = q + dirY[i];

if(isValid(newX, newY) && mat[newX][newY] == 1 && vis[newX][newY] == 0){


/* Horizontal Cost */
if(i == 0 || i == 2){
dis[newX][newY] = dis[p][q];
}
else if(i == 1 || i == 3){
dis[newX][newY] = 1 + dis[p][q];
}

vis[newX][newY] = 1;

queue[rear].x = newX;
queue[rear].y = newY;
rear = (rear + 1) % QS;
}
}
}
cout << dis[tX][tY];
}

int main(){
cin >> n;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> mat[i][j];
vis[i][j] = 0;
dis[i][j] = 0;
}
}

cin >> sX >> sY >> tX >> tY;

calculateFrogJump();
return 0;
}

Q15: JEWEL MAZE:


There is a maze that has one entrance and one exit. Jewels are placed in passages of the maze.
You want to pick up the jewels after getting into the maze through the entrance and before getting
out of it through the exit. You want to get as many jewels as possible, but you don’t want to take
the same passage you used once.

When locations of a maze and jewels are given, find out the greatest number of jewels you can get
without taking the same passage twice, and the path taken in this case.

Input
There can be more than one test case in the input file. The first line has T, the number of test cases.
Then the totally T test cases are provided in the following lines (T ≤ 10 ).

In each test case, In the first line, the size of the maze N (1 ≤ N ≤ 10) is given.
The maze is N×N square-shaped. From the second line through N lines, information of the maze is given.
“0” means a passage, “1” means a wall, and “2” means a location of a jewel. The entrance is located
on the upper-most left passage and the exit is located on the lower-most right passage.
There is no case where the path from the entrance to the exit doesn’t exist.

Output
From the first line through N lines, mark the path with 3 and output it. In N+1 line, output the
greatest number of jewels that can be picked up. Each test case must be output separately as a empty.
*/

#include<iostream>
#include<climits>
#define MAX 21
using namespace std;

int n, ans;

bool isValid(int i, int j){


return (i>=0 && i<n && j>=0 && j<n);
}

void printMatrix(int **arr){


for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}

int dirX[] = {1,0,-1,0};


int dirY[] = {0,1,0,-1};

void jewelMaze(int **maze, int x, int y, int value, int **visited, int **path){
if(x == n-1 && y == n-1){
if(value >= ans){
ans = value;

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


for(int j=0; j<n; j++)
if(visited[i][j]){
path[i][j] = 3;
}
else{
path[i][j] = maze[i][j];
}
}
}
return;
}

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


int newX = x + dirX[i];
int newY = y + dirY[i];

if(isValid(newX, newY)){

if(visited[newX][newY] == 0 && maze[newX][newY] == 0){


visited[newX][newY] = 1;
jewelMaze(maze, newX, newY, value, visited, path);
visited[newX][newY] = 0;
}

if(visited[newX][newY] == 0 && maze[newX][newY] == 2){


visited[newX][newY] = 1;
jewelMaze(maze, newX, newY, value+1, visited, path);
visited[newX][newY] = 0;
}

}
}

int main(){
int t;
cin >> t;
while(t--){
cin >> n;
int **maze = new int * [n + 1];
for(int i=0; i<n; i++){
maze[i] = new int[n + 1];
}

int **visited = new int * [n + 1];


for(int i=0; i<n; i++){
visited[i] = new int[n + 1];
}

int **path = new int * [n + 1];


for(int i=0; i<n; i++){
path[i] = new int[n + 1];
}

// Cleaner and input Maze


for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> maze[i][j];
visited[i][j] = 0;
path[i][j] = 0;
}
}

ans = INT_MIN;

int sX = 0, sY = 0;
visited[sX][sY] = 1;

// printMatrix(maze);

if(maze[sX][sY] == 2)
jewelMaze(maze, sX, sY, 1, visited, path);
else
jewelMaze(maze, sX, sY, 0, visited, path);

cout << "Jewel collected : " << ans << endl;

cout << "Path traversed --> " << endl;


printMatrix(path);

cout << endl;


}
return 0;
}

Q16. LAUGHING GAS


There is a maze that has one entrance and one exit. Jewels are placed in passages of the maze.
You want to pick up the jewels after getting into the maze through the entrance and before getting
out of it through the exit. You want to get as many jewels as possible, but you don’t want to take
the same passage you used once.

When locations of a maze and jewels are given, find out the greatest number of jewels you can get
without taking the same passage twice, and the path taken in this case.

Input
There can be more than one test case in the input file. The first line has T, the number of test cases.
Then the totally T test cases are provided in the following lines (T ≤ 10 ).

In each test case, In the first line, the size of the maze N (1 ≤ N ≤ 10) is given.
The maze is N×N square-shaped. From the second line through N lines, information of the maze is given.
“0” means a passage, “1” means a wall, and “2” means a location of a jewel. The entrance is located
on the upper-most left passage and the exit is located on the lower-most right passage.
There is no case where the path from the entrance to the exit doesn’t exist.

Output
From the first line through N lines, mark the path with 3 and output it. In N+1 line, output the
greatest number of jewels that can be picked up. Each test case must be output separately as a empty.
*/

#include<iostream>
#include<climits>
#define MAX 21
using namespace std;

int n, ans;

bool isValid(int i, int j){


return (i>=0 && i<n && j>=0 && j<n);
}

void printMatrix(int **arr){


for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}

int dirX[] = {1,0,-1,0};


int dirY[] = {0,1,0,-1};

void jewelMaze(int **maze, int x, int y, int value, int **visited, int **path){
if(x == n-1 && y == n-1){
if(value >= ans){
ans = value;

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


for(int j=0; j<n; j++)
if(visited[i][j]){
path[i][j] = 3;
}
else{
path[i][j] = maze[i][j];
}
}
}
return;
}

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


int newX = x + dirX[i];
int newY = y + dirY[i];

if(isValid(newX, newY)){

if(visited[newX][newY] == 0 && maze[newX][newY] == 0){


visited[newX][newY] = 1;
jewelMaze(maze, newX, newY, value, visited, path);
visited[newX][newY] = 0;
}
if(visited[newX][newY] == 0 && maze[newX][newY] == 2){
visited[newX][newY] = 1;
jewelMaze(maze, newX, newY, value+1, visited, path);
visited[newX][newY] = 0;
}

}
}

int main(){
int t;
cin >> t;
while(t--){
cin >> n;
int **maze = new int * [n + 1];
for(int i=0; i<n; i++){
maze[i] = new int[n + 1];
}

int **visited = new int * [n + 1];


for(int i=0; i<n; i++){
visited[i] = new int[n + 1];
}

int **path = new int * [n + 1];


for(int i=0; i<n; i++){
path[i] = new int[n + 1];
}

// Cleaner and input Maze


for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> maze[i][j];
visited[i][j] = 0;
path[i][j] = 0;
}
}

ans = INT_MIN;

int sX = 0, sY = 0;
visited[sX][sY] = 1;

// printMatrix(maze);

if(maze[sX][sY] == 2)
jewelMaze(maze, sX, sY, 1, visited, path);
else
jewelMaze(maze, sX, sY, 0, visited, path);

cout << "Jewel collected : " << ans << endl;


cout << "Path traversed --> " << endl;
printMatrix(path);

cout << endl;


}
return 0;
}

Q17. MR KIM
/*
Mr. Kim has to deliver refrigerators to N customers. From the office, he is going to visit all the customers and then
return to his home.
Each location of the office, his home, and the customers is given in the form of integer coordinates (x,y) (0≤x≤100,
0≤y≤100) .
The distance between two arbitrary locations (x1, y1) and (x2, y2) is computed by |x1-x2| + |y1-y2|, where |x| denotes
the absolute value
of x; for instance, |3|=|-3|=3. The locations of the office, his home, and the customers are all distinct. You should plan
an optimal way
to visit all the N customers and return to his among all the possibilities.
You are given the locations of the office, Mr. Kim’s home, and the customers; the number of the customers is in the
range of 5 to 10.
Write a program that, starting at the office, finds a (the) shortest path visiting all the customers and returning to his
home.
Your program only have to report the distance of a (the) shortest path.

Constraints

5≤N≤10. Each location (x,y) is in a bounded grid, 0≤x≤100, 0≤y≤100, and x, y are integers.

Input

You are given 10 test cases. Each test case consists of two lines; the first line has N, the number of the customers,
and the
following line enumerates the locations of the office, Mr. Kim’s home, and the customers in sequence. Each location
consists of
the coordinates (x,y), which is reprensented by ‘x y’.

Output

Output the 10 answers in 10 lines. Each line outputs the distance of a (the) shortest path. Each line looks like ‘#x
answer’
where x is the index of a test case. ‘#x’ and ‘answer’ are separated by a space.

I/O Example

Input (20 lines in total. In the first test case, the locations of the office and the home are (0, 0) and (100, 100)
respectively,
and the locations of the customers are (70, 40), (30, 10), (10, 5), (90, 70), (50, 20).)

5 ← Starting test case #1


0 0 100 100 70 40 30 10 10 5 90 70 50 20

6 ← Starting test case #2

88 81 85 80 19 22 31 15 27 29 30 10 20 26 5 14

10 ← Starting test case #3

39 9 97 61 35 93 62 64 96 39 36 36 9 59 59 96 61 7 64 43 43 58 1 36

Output (10 lines in total)

#1 200

#2 304

#3 366
*/
#include<iostream>
#include<climits>
using namespace std;
int x[20],y[20],n,ans;

int abs(int i){//Absolute function


if(i>0){
return i;
}
return -i;
}

int dist(int i, int j){//Calc dist between 2 points


int x1 = x[i], x2 = x[j];
int y1 = y[i], y2 = y[j];

return (abs(x1-x2) + abs(y1-y2));


}

void optimalPath(int x,bool visited[],int nodes,int value){


if(n == nodes){//If number of nodes equal n then set value of answer
ans = min(ans,value + dist(x,n+1));
}
for(int i=1;i<=n;i++){
if(!visited[i]){
visited[i] = true;
optimalPath(i,visited,nodes+1,value + dist(x,i));//Dfs call
visited[i] = false;
}
}
}

int main(){
int tCases;
cin >> tCases;//For testcases
for(int i=0;i<tCases;i++){
ans=INT_MAX;//Set ans to max value
cin >> n;
cin >> x[n+1] >> y[n+1] >> x[0] >> y[0];//Input destination and source x,y coordinates
for(int i=1;i<=n;i++){//Input drop off location coordinates
cin >> x[i] >> y[i];
}
bool visited[n+2]={false};
optimalPath(0,visited,0,0);
cout << "#" << i+1 << " " << ans << endl;
}
return 0;
}

/*
#include <iostream>
#include <cstring>
using namespace std;

bool marked[105][105];

struct point {
int x;
int y;
};

int absDiff(point i, point j)


{
int xd = (i.x > j.x) ? i.x - j.x : j.x - i.x ;
int yd = (i.y > j.y) ? i.y - j.y : j.y - i.y ;
return xd + yd ;
}

int solve(point a, point b, point arr[], point &end, int nodes)


{
int curDist = absDiff(a, b);
marked[b.x][b.y] = 1;
int dist = 0, minDist = 1000007 ;
for(int i = 0; i < nodes; i++){
if(marked[arr[i].x][arr[i].y] == 0){
dist = solve(b, arr[i], arr, end, nodes);
if(dist < minDist)
minDist = dist ;
}
}
marked[b.x][b.y] = 0;
if(minDist == 1000007){
minDist = absDiff(b, end);
}

return curDist + minDist ;


}

int main()
{
int test;
cin >> test ;
for(int l = 1; l <= test; l++){

int nodes;
cin >> nodes ;
point start, end;
point arr[nodes + 3];

cin >> start.x >> start.y ;


cin >> end.x >> end.y ;

for(int u = 0; u < nodes; u++){


cin >> arr[u].x >> arr[u].y ;
}

int dist = 0, minDist = 100007 ;


for(int i = 0; i < nodes; i++){
memset(marked, 0, sizeof(bool) * (nodes + 2) * (nodes + 2));
dist = solve(start, arr[i], arr, end, nodes);
if(dist < minDist)
minDist = dist ;
}

cout << "#" << l << " " << minDist << endl ;
}
return 0;
}
*/

Q18. MR LEE
/*
Mr. Lee has to travel various offices abroad to assist branches of each place. But he has a problem.
The airfare would be real high as all offices he has to visit are in foreign countries. He wants to visit every
location only one time and return home with the lowest expense. Help this company-caring man calculate the lowest
expense.

Input format
Several test cases can be included in the inputs. T, the number of cases is given in the first row of the inputs.
After that, the test cases as many as T (T ≤ 30) are given in a row. N, the number of offices to visit is given on
the first row per each test case. At this moment, No. 1 office is regarded as his company (Departure point).
(1 ≤ N ≤ 12) Airfares are given to move cities in which branches are located from the second row to N number rows.
i.e. jth number of ith row is the airfare to move from ith city to jth city. If it is impossible to move between
two cities, it is given as zero.

Output format
Output the minimum airfare used to depart from his company, visit all offices, and then return his company on the
first row per each test case.

Example of Input
3
5
0 14 4 10 20
14 0 7 8 7
4 5 0 7 16
11 7 9 0 2
18 7 17 4 0
5
99295
63515
18333
60968
66948
3
0 2 24
302
040

Example of Output

30
18
CUSTOM - 31 <- 4
*/
#include<iostream>
#include<climits>
using namespace std;

int N, result;

void minCostMrLee(int **arr, bool *visited, int count, int cost, int src){
// Base Case
if(count == N-1){
/* Corner Case if no path exists from last city */
if(arr[src][0] != 0)
result = min(result, cost + arr[src][0]);
return;
}

// Main Case
for(int i=0; i<N; i++){
if(!visited[i] && arr[src][i] != 0){
visited[i] = true;
minCostMrLee(arr, visited, count + 1, cost + arr[src][i], i);
visited[i] = false;
}
}
}

int main(){
int t;
cin >> t;
while(t--){
cin >> N;
int **arr = new int*[N];
for(int i=0; i<N; i++){
arr[i] = new int[N];
}
bool *visited = new bool[N];

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


visited[i] = false;
for(int j=0; j<N; j++){
cin >> arr[i][j];
}
}

result = INT_MAX;

visited[0] = true;

minCostMrLee(arr, visited, 0, 0, 0);


result != INT_MAX ? cout << result << "\n" : cout << "-1\n";
}
return 0;
}

/*
#include<iostream>
using namespace std;
int arr[1000][1000];
bool visited[1000];
int ans = 1000000;
void dfs(int n,int count,int cost,int last)
{
//cout<<last<<" ";
if(count==n)
{
//cout<<endl;
int cost1 = cost + arr[last][0];
if(cost1<ans)
ans = cost1;
}
for(int i=1;i<n;i++)
{
if(visited[i])
continue;
if(arr[last][i]==0)
continue;
visited[i]=true;
int cost1 = cost + arr[last][i];
dfs(n,count+1,cost1,i);
visited[i]=false;
}
return;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
ans = 1000000;
cin>>n;
for(int i=0;i<n;i++)
visited[i]=false;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
dfs(n,1,0,0);
cout<<ans<<endl;
}
}
*/

Q19. OIL MINE


/*
There is an island surrounded by oil mines. You will be given n companies and m oil mines having values.
You have to distribute the mines to "n" companies in fair manner. Remember the companies can have oil
mines adjacent to each other and not in between of each others.After distributing them compute the
difference of oil mines from the company getting highest and company getting lowest. This number
should be minimum.(then only the distribution can be termed as fair).

Input
2
24
6 13 10 2
24
6 10 13 2

output
5
1
*/

#include <iostream>
#include <climits>
using namespace std;

int companies, mines, ANS;

int MIN(int x, int y){


return (x>=y) ? y : x;
}
int MAX(int x, int y){
return (x>=y) ? x : y;
}

void calculateOilMines(int i, int *oilMines, bool *visited, int minV, int maxV, int sum,
int nodes, int &ANS){
// Base Case
if(visited[i]){
int newMin = MIN(sum, minV);
int newMax = MAX(sum, maxV);

if(nodes == companies - 1){


ANS = min(ANS, newMax - newMin);
}
return;
}

// Main Case
visited[i] = 1;
int j = (i + 1) % mines;

calculateOilMines(j, oilMines, visited, minV, maxV, sum + oilMines[i], nodes, ANS);

int newMin = MIN(sum, minV);


int newMax = MAX(sum, maxV);

calculateOilMines(j, oilMines, visited, newMin, newMax, oilMines[i], nodes + 1, ANS);

visited[i] = 0;
return;
}

int main() {
// your code goes here
int t;
cin >> t;
while(t--){
cin >> companies >> mines;
int *oilMines = new int[mines + 1];
bool *visited = new bool[mines + 1];

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


cin >> oilMines[i];
visited[i] = 0;
}

ANS = INT_MAX;
for(int i=0; i<mines; i++)
calculateOilMines(i, oilMines, visited, INT_MAX, INT_MIN, 0, 0, ANS);

cout << ANS <<endl;


}
return 0;
}
/*
#include<bits/stdc++.h>
using namespace std;
int ans=9999;
void findMinDiff(int company[],int n)
{
int mini = 9999;
int maxi=0;
for(int i=0;i<n;i++)
{
mini = min(mini,company[i]);
maxi = max(maxi,company[i]);
}
if(ans>(maxi-mini))
ans = maxi-mini;
}
void findAns(int end,int curr,int oil[],int company[],int m,int n,int num)
{
if((curr+1)%m==end)
{
for(int j = num;j<n;j++)
{
company[j]+=oil[curr];
findMinDiff(company,n);
company[j]-=oil[curr];
}
return;
}
if(num==n)
return;
company[num]+=oil[curr];
findAns(end,(curr+1)%m,oil,company,m,n,num);
company[num]-=oil[curr];
findAns(end,curr,oil,company,m,n,num+1);
}
int main()
{
int t;
cin>>t;
while(t--)
{
ans=9999;
int n,m;
cin>>n>>m;
int oil[m];
for(int i=0;i<m;i++)
cin>>oil[i];
int company[n];
for(int i=0;i<n;i++)
{
company[i]=0;
}
for(int i=0;i<m;i++)
{
findAns(i,i,oil,company,m,n,0);
}
cout<<ans<<endl;
}
}
*/

Q20. OLD PHONE


/*
https://www.careercup.com/question?id=5680648437104640

You are given an old touch smartphone numbers having dial pad and calculator app.
Aim: The goal is to type a number on dialpad.

But as phone is old, some of the numbers and some operations can't be touched.
For eg. 2,3,5,9 keys are not responding , i.e you cannot use them
But you can always make a number using other numbers and operations in Calculator. There could be multiple ways
of making a number

Calculator have 1-9 and +,-,*,/,= as operations. Once you have made the number in Calculator you can copy the
number and use it.

You have to find minimum number to touches required to obtain a number.

#Input:#
There will be multiple Test cases .Each test case will consist of 4 lines
1) First line will consist of N,M,O
N: no of keys working in Dialpad (out of 0,1,2,3,4,5,6,7,8,9)
M:types of operations supported (+,-,*,/)
O: Max no of touches allowed
2) second line of input contains the digits that are working e.g 0,2,3,4,6.
3) Third line contains the valued describing operations, 1(+),2(-),3(*),4(/)
4) fourth line contains the number that we want to make .

#Output:#
Output contains 1 line printing the number of touches required to make the number

#Sample Test Case:#


5
535
12460
123
5
645
124698
1234
91
624
013579
124
28
5 2 10
12678
23
981
635
146789
123
18

#Output:#
4
2
5
9
2

If you have to type 18-> 2 operations. (Each touch is considered an operation),br> If you have to type 5 -> '1+4=' that
requires 4 operations. There could be other ways to make '5'.
*/

#include<iostream>
#include<math.h>
using namespace std;
int *working,*operations;
int answer=INT_MAX;
int n,m,o;
int eval(int prev,int curr,int op){
if(prev==-10000000){
return curr;
}

if(op==1){
return prev+curr;
}
if(op==2){
return prev-curr;
}
if(op==3){
return prev*curr;
}
if(op==4){
if(curr==0){
return -1;
}else{
return prev/curr;
}
}
}
bool isDone(int prev,int curr,int Operation,int target){
if(Operation==4 && curr==0){
return false;
}

if(eval(prev,curr,Operation)==target)
return 1;
return false;
}
void findMinTouch(int prev,int curr,int ooperation,int tou,int t)
{ if(ooperation!=-1 && curr!=-10000000)
{
bool k=isDone(prev,curr,ooperation,t);
if(k && tou<o )
{
if(answer>tou+1)
answer=tou+1;
}
}
if(prev==t && tou<o && ooperation !=-1 && curr==-10000000)
{
answer=min(answer,tou);

}
if(ooperation==-1 && curr==t && tou<o )
{
answer=min(answer,tou);
}
if(tou>o) return ;

for(int i=0;i<m;i++)
{
if(curr==-10000000)
break;
if(curr==0 && ooperation==4) continue;
int val=eval(prev,curr,ooperation);
findMinTouch(val,-10000000,operations[i],tou+1,t);
}
for(int i=0;i<n;i++)
{
if(curr==-10000000)
{
findMinTouch(prev,working[i],ooperation,tou+1,t);
}
else
{
int val=abs(curr);
val=val*10+working[i];
if(curr<0){
val*=-1;
}
findMinTouch(prev,val,ooperation,tou+1,t);
}
}
}
int main(){
int t;
cin>>t;
int count = 0;
while(t--){
answer=INT_MAX;
cin>>n>>m>>o;
working=new int[n + 2];
for(int i=0;i<n;i++){
cin>>working[i];
}
operations=new int[m + 2];
for(int i=0;i<m;i++){
cin>>operations[i];
}

int target;
cin>>target;

findMinTouch(-10000000,-10000000,-1,0,target);
count++;
cout<<"#" << count << ": " << answer<<endl;
}
return 0;
}

Q21. OMNIUS NUMBER


Company A is discarding product numbers that contain few specific digits a specific number of time or
more than that. You are given a range and you need to find product numbers that are possible.

Example-

Range: 24 to 12943

Numbers that should not come: 1, 3, 5


Number of times these number should not occur: 3 or more

In above case all two digit numbers are valid.

In three digit: 111, 113, 115, 311, 331, 333, 511, 533, 555 are not valid.

In four digit: All the numbers containing above 3 digit numbers are not valid.

Eg: 11223 is not valid, 11222 is valid.


*/

#include <iostream>
using namespace std;

int numberOminous(int a, int b, int k, int *delNos, int n){


int count = 0;
for(int i = a; i <= b; i++){
int temp = i;
int digitArray[10] = {0};
while(temp){
digitArray[temp%10]++;
temp /= 10;
}

int rougeK = 0;
for(int i=0; i<n; i++){
rougeK += digitArray[delNos[i]];
}

if(rougeK < k){


count++;
}

}
return count;
}

int main() {
int a, b, k;
cin >> a >> b >> k;
int n;
cin >> n;
int *delNos = new int[n];
for(int i=0; i<n; i++){
cin >> delNos[i];
}

cout << numberOminous(a, b, k, delNos, n) << "\n";

return 0;
}

Q22. PILLER PIPE


You have to place an electronic banner of a company as high as it can be, so that whole the city can view the banner
standing on top of TWO PILLERS.
The height of two pillers are to be chosen from given array.. say [1, 2, 3, 4, 6]. We have to maximise the height
of the two pillars standing side by side, so that the pillars are of EQUAL HEIGHT and banner can be placed on top of it.
In the above array, (1, 2, 3, 4, 6) we can choose pillars like this, say two pillars as p1 and p2.
In case, there is no combination possible, print 0.

INPUT :
1
5
12346
Output :
8
*/

#include <iostream>
using namespace std;

void solve(int a[], int vis[], int p1, int p2, int n, int &ans){
if(p1 == p2){
if(p1 > ans){
ans = p1;
}
}

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


if(vis[i] == 0){
vis[i] = 1;
solve(a, vis, p1 + a[i], p2, n, ans);
solve(a, vis, p1, p2 + a[i], n, ans);
vis[i] = 0;
}
}
}

int main(){
int n;
cin>>n;
int a[n];

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


cin>>a[i];
}

int vis[n] = {0};


int ans = -1;
solve(a,vis,0,0,n,ans);

cout<<ans;
}

Q23. RESEARCH TEAM:


/*
A Research team want to establish a research center in a region where they found some rare-elements.
They want to make it closest to all the rare-elements as close as possible so that they can reduce
overall cost of research over there. It is given that all the rare-element’s location is connected
by roads. It is also given that Research Center can only be build on road. Team decided to assign
this task to a coder. If you feel you have that much potential.

Here is the Task :- Find the shortest of the longest distance of research center from given locations
of rare-elements.

Locations are given in the matrix cell form where 1 represents roads and 0 no road.
Number of rare-element and their location was also given(number<=5) and order of square matrix
was less than equal to (20).
*/

/*
For this you have to implement bfs for every position where road exist to find the distance of
every research center or do Vice-versa. for each position store maximum distance of all distances
to research center and the compare each maximum distance to find minimum of them
Input -
6
52
43
34
11000
11000
11111
11101
11111
82
56
64
11111100
11111110
11010110
11110110
11111110
11111110
00000000
00000000
10 3
82
53
71
0001111110
1111111110
1001000010
1111111111
1111010011
1111010011
1111010011
1111111111
1110010011
1111111111
15 4
11 15
15 9
12
14 3
111111111111111
101111111111101
101000100001101
101000100001101
101111111111111
101000100001101
101000111111111
101000100001101
101000100001101
101000100001101
101000100001101
101000100001101
111111111111111
001000111111101
001111111111111
20 4
13 6
20 4
12
17 16
11111111111111100000
10111111111111100000
10100000001001100000
10100000001001100000
11111111111111110000
10100000001001110000
10100000001001110000
11111111111111111111
10100000001001110011
10100000001001110011
10100000001001110011
10100000001001110011
10111111111111110011
10100000001000110011
10100000001000110011
10100000001000110011
10100000001000110011
11111111111111111111
11111111111111111111
11111111111000000000
52
21
35
10111
11101
01101
01011
11101

Output -
1
2
2
12
15
4
*/

#include <stdio.h>
int Answer = 9999;
int region[22][22];
int visited[22][22];
int N, C;
int location[5][2];
int rear = -1;
int front = -1;
struct queue {
int row;
int col;
}Q[10000];

void init()
{
int m,n;
rear = -1;
front = -1;
for(m = 0; m < 22; m++)
{
for(n = 0; n < 22; n++)
{
visited[m][n] = 0;
}
}

for(m = 0; m < 10000; m++)


{
Q[m].row = 0;
Q[n].col = 0;
}
}

void discover(int row, int col, int val)


{
int l, m, k;
int cnt = 0;

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


{
if(visited[location[k][0]][location[k][1]] > 0)
cnt++;
}
if(cnt >= C)
return;

if((row-1) >= 1 && visited[row-1][col] == 0 && (region[row-1][col] == 1 || region[row-1][col] == 3))


{
visited[row-1][col] = val+1;
++rear;
Q[rear].row = row-1;
Q[rear].col = col;
}
if((row+1) <= N && visited[row+1][col] == 0 && (region[row+1][col] == 1 || region[row+1][col] == 3))
{
visited[row+1][col] = val+1;
++rear;
Q[rear].row = row+1;
Q[rear].col = col;
}
if((col-1) >= 1 && visited[row][col-1] == 0 && (region[row][col-1] == 1 || region[row][col-1] == 3))
{
visited[row][col-1] = val+1;
++rear;
Q[rear].row = row;
Q[rear].col = col-1;
}
if((col+1) <= N && visited[row][col+1] == 0 && (region[row][col+1] == 1 || region[row][col+1] == 3))
{
visited[row][col+1] = val+1;
++rear;
Q[rear].row = row;
Q[rear].col = col+1;
}

while(front<rear)
{
++front;
discover(Q[front].row, Q[front].col, visited[Q[front].row][Q[front].col]);
}

int main(void){
int T, test_case;

scanf("%d", &T);
for(test_case = 0; test_case < T; test_case++)
{
int i,j,k;
int x,y,c;
int temp = 0;

Answer = 9999;

scanf("%d%d", &N, &C);

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


{
scanf("%d%d", &x, &y);
location[i][0] = x;
location[i][1] = y;
}

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


{
for(j = 1; j <= N; j++)
{
scanf("%d", &region[i][j]);
}
}
for(k = 0; k < C; k++)
{
region[location[k][0]][location[k][1]] = 3;
}

init();
Answer = 9999;
for(i = 1; i <= N; i++)
{
for(j = 1; j <= N; j++)
{
init();
temp = 0;
if(region[i][j] == 1)
{
visited[i][j] = 1;
discover(i, j, 1);
for(k = 0; k < C; k++)
{
if(temp < visited[location[k][0]][location[k][1]])
temp = visited[location[k][0]][location[k][1]];
}
if(Answer > temp)
Answer = temp;
}

}
}
printf("#%d %d\n", test_case+1, Answer-1);
}
return 0;
}

Q24. SINKHOLE
Q.There is a large plot with various sinkholes present.
Since one sinkhole can combine with another sinkhole, it is required to get
at most one sinkhole while occupying the plot. You have to find the maximum
square-area formed with at most one sinkhole present.
If there are two plots with the same area then print the one with
lesser sinkhole present otherwise if the sinkholes are also same then print
anyone. For each case, you have to print the bottom leftmost coordinate and
top rightmost point. Please keep in mind that the plot starts with (1, 1).

Time limit= 1sec and Memory limit– 256Mb

Input: First line will give the number of test cases. For each test case, we
will be given the size of the plot matrix N x M (where 1<=N, M<=1000). Next
line will give the number of sinkholes present in the matrix K (1<=K<=N+M).
Next, K-lines will give the coordinates of the sinkholes.

Output: For each test case, you have to print the number of the test case
and the coordinates of the resultant square.
i.e. #i xb yb xt yt (ith test case, xb=bottomost left x-coordinate,
yb=bottomost left y-coordinate, xt= topmost right x-coordinate,
yt= topmost right y-coordinate)

* time complexity of my approach = O(n*m*log(min(m,n))) *


*/
#include <iostream>
using namespace std;

#define INT_MAX 100000;

int xb,yb,xt,yt;

int fun(int dp[][1001], int N, int M, int k){


int msum = INT_MAX;
for(int i=0; i<=N-k; i++){
for(int j=0; j<=M-k; j++){
int sum = dp[i+k][j+k]-dp[i+k][j]-dp[i][j+k]+dp[i][j];
if(sum < msum){
msum = sum;
if(msum <=1){
xb = i+k;
yb = j+1;
xt = i+1;
yt = j+k;
}
}
}
}
return msum;
}

int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
/* input */
int N,M;
cin>>N>>M;
int A[N][M];
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
A[i][j]=0;
}
}
int K;
cin>>K;
for(int i=0; i<K; i++){
int x,y;
cin>>x>>y;
A[x-1][y-1]=1;
}

int dp[1001][1001]; /* dp[i][j] = sum of submatrix top-left(0,0) to bottom-right(i,j) */


for(int i=0; i<1001; i++){
for(int j=0; j<1001; j++){
dp[i][j]=0;
}
}
for(int i=1; i<=N; i++){
for(int j=1; j<=M; j++){
dp[i][j] = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+A[i-1][j-1];
}
}
/* applying binary search */
int l=1, r=min(M,N);
int ones;
while(l<r){
int mid = (l+r)/2;
ones = fun(dp,N,M,mid);
//if no. of ones > 1 means we need to decrease the submatix size
if(ones >1){
r = mid;
}
//else increase the submatrix size
else{
l = mid+1;
}
}
/* output */
cout<<xb<<" "<<yb<<" "<<xt<<" "<<yt<<endl;
return 0;
}

Q25. SPACESHIP BOMB:


You’ll be given a grid as below:

01020
02221
02111
10100
00122
11001
xxSxx

In the grid above,


1: This cell has a coin.
2: This cell has an enemy.
0: It contains nothing.

The highlighted(yellow) zone is the control zone. S is a spaceship that we need to control so that we can get
maximum coins.
Now, S’s initial position will be at the center and we can only move it right or left by one cell or do not move.
At each time, the non-highlighted part of the grid will move down by one unit.
We can also use a bomb but only once. If we use that, all the enemies in the 5×5 region above the control zone
will be killed.
If we use a bomb at the very beginning, the grid will look like this:

01020
00001
00111
10100
00100
11001
xxSxx

As soon as, the spaceship encounters an enemy or the entire grid has come down, the game ends.
For example,
At the very first instance, if we want to collect a coin we should move left( coins=1). This is because when the
grid comes down by 1 unit we have a coin on the second position and by moving left we can collect that coin.
Next, we should move right to collect another coin (coins=2).
After this, remain at the same position (coins=4).
This is the current situation after collecting 4 coins.

0102001000
0 2 2 2 1 -->after using 0 0 0 0 1
x x S x x -->bomb x x S x x

Now, we can use the bomb to get out of this situation. After this, we can collect at most 1 coin. So maximum
coins=5.
*/
#include<bits/stdc++.h>
using namespace std;
void updateMatrix(int row,char ** matrix){
if(row<0){
return;
}
int upLimit=max(0,row-4);
for(int i=row;i>=upLimit;i--){
for(int j=0;j<=4;j++){
if(matrix[i][j]=='2'){
matrix[i][j]='0';
}
}
}
}
int findMaxPoints(int row,int col,int bombs,char ** matrix){
if(row<=0 || col<0 || col>=5){
return 0;
}
int answer=0;
if(row>0 && matrix[row-1][col]!='2'){
answer=max(answer,(matrix[row-1][col]=='1'?1:0)+findMaxPoints(row-1,col,bombs,matrix));
}
if(col>0 && row>0 && matrix[row-1][col-1]!='2'){
answer=max(answer,(matrix[row-1][col-1]=='1'?1:0)+findMaxPoints(row-1,col-1,bombs,matrix));
}
if(col<4 && row>0 && matrix[row-1][col+1]!='2'){
answer=max(answer,(matrix[row-1][col+1]=='1'?1:0)+findMaxPoints(row-1,col+1,bombs,matrix));
}

if(answer==0 && bombs>0){


updateMatrix(row-1,matrix);
answer=findMaxPoints(row,col,bombs-1,matrix);
}

return answer;
}
int main(){
int t, row;
cin >> t;
int tNo = 0;
while(t--){
cin >> row;
char ** matrix=new char*[row + 2];
for(int i=0; i<row; i++){
matrix[i]=new char[5];
for(int j=0;j<5;j++){
cin>>matrix[i][j];
}
}
tNo++;
cout<< "#" << tNo << " : " << findMaxPoints(row,2,1,matrix) << endl;
}
return 0;
}

/*
No rech top

#include <iostream>
using namespace std;
int det[5][5];
int mat[13][5];

void detonate(int r)
{
for(int i=r;i>r-5 && i>=0;i--)
{
for(int j=0;j<5;j++)
{
det[r-i][j]=0;
if(mat[i][j]==2)
{
det[r-i][j]=2;
mat[i][j]=0;
}
}
}
}

void undet(int r)
{
for(int i=r;i>r-5 && i>=0;i--)
for(int j=0;j<5;j++)
{
if( det[r-i][j]==2)
mat[i][j]=2;
}
}
void func(int n,int pos,int c,int &max)
{
if(pos>4||pos<0||c<0)
return;

if(mat[n][pos]==2)
c-=1;
else if(mat[n][pos]==1)
c+=1;

if(n==0)
{
if(c>max)
max=c;
return;
}
else
{
func(n-1,pos+1,c,max);
func(n-1,pos-1,c,max);
func(n-1,pos,c,max);
}
}
int main()
{
int t;
cin>>t;
int count=1;
while(t--)
{
int n;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<5;j++)
cin>>mat[i][j];
int max=-1,c;
for(int j=0;j<5;j++)
mat[n][j]=0;
mat[n][2]=3;
for(int j=n;j>=5;j--)
{
c=-1;
detonate(j-1);
func(n,2,0,c);
if(c>max)
max=c;
undet(j-1);
}
if(max<0)
max=-1;
cout<<"#"<<count<<" "<<max<<endl;
count++;
}
}
*/

/*
#include <iostream>
using namespace std;
int det[5][5];
int mat[13][5];

void detonate(int r){


for(int i=r;i>r-5 && i>=0;i--){
for(int j=0;j<5;j++){
det[r-i][j]=0;
if(mat[i][j]==2){
det[r-i][j]=2;
mat[i][j]=0;
}
}
}
}

void undet(int r){


for(int i=r;i>r-5 && i>=0;i--)
for(int j=0;j<5;j++){
if( det[r-i][j]==2)
mat[i][j]=2;
}
}

void func(int n,int pos,int c,int &max){


if(pos>4||pos<0||c<0)
return;

if(mat[n][pos]==2)
c-=1;
else if(mat[n][pos]==1)
c+=1;

if(n==0){
if(c>max)
max=c;
return;
}
else{
func(n-1,pos+1,c,max);
func(n-1,pos-1,c,max);
func(n-1,pos,c,max);
}
}

int main(){
int t;
cin>>t;
int count=1;
while(t--){
int n;
cin>>n;

for(int i=0;i<n;i++)
for(int j=0;j<5;j++)
cin>>mat[i][j];
for(int j=0;j<5;j++)
mat[n][j]=0;
mat[n][2]=3;

int max=-1,c;
for(int j=n;j>=5;j--){
c=-1;
detonate(j-1);
func(n,2,0,c);

if(c>max)
max=c;

undet(j-1);
}

if(max<0)
max=-1;

cout<<"#"<<count<<" "<<max<<endl;
count++;
}
}
*/

Q26. STRING COMPRESSION:

#include <iostream>
using namespace std;

int lengthOfString(char *str){


int len = 0, i = 0;
while(str[i] != '\0'){
len++;
i++;
}
return len;
}

void mergeAplha(char *str){


int lenString = lengthOfString(str);
int hash[26] = {0};

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


char letter = str[i];
i++;

int temp = 0;
while(i<lenString && str[i] >= '0' && str[i] <= '9'){
temp = (temp * 10) + (str[i]-'0');
i++;
}
i--;

hash[letter - 'a'] += temp;


}

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


if(hash[i] != 0){
char temp = i + 'a';
cout << temp << " " << hash[i] << " ";
}
}

int main() {
char s[100];
cin >> s;
mergeAplha(s);
return 0;
}

Q27. SUM LEVEL K:


#include<bits/stdc++.h>
using namespace std;

typedef long long int LL;

#define scll(x) scanf("%lld",&x);


#define sci(x) scanf("%d",&x);
#define prll(x) printf("%lld\n",x);
#define pri(x) printf("%d\n",x);

/*
3
(0(5(6()())(-4()(9()())))(7(1()())(3()())))
*/

int main()
{
int arr[2][100]={0};
int size = 0;
int x;
string str;

cin>>x;
cin>>str;
int level=0, temp=0, commit=0, neg=0;
for(int i=0; i<str.length(); i++){

if(str[i]=='(' || str[i]==')'){
if(commit == 1){
if(neg==1){
temp=temp*-1;
neg=0;
}

arr[0][size]=level;
arr[1][size]=temp;
size++;
temp=0;
}

if(str[i]=='('){
level++;
}
else if(str[i]==')'){
level--;
}
commit=0;
}
else if(str[i]=='-'){
neg=1;
commit = 1;
}
else{
temp= temp*10 + str[i] - '0';
commit = 1;
}

int temp0,temp1;
for(int i=0;i<size-1;i++){
for(int j=i+1; j<size; j++){
if(arr[0][j] > arr[0][i]){
temp0=arr[0][j];
temp1=arr[1][j];
arr[0][j]=arr[0][i];
arr[1][j]=arr[1][i];
arr[0][i]=temp0;
arr[1][i]=temp1;
}

}
}
int sum = 0;
for(int i=0;i<size;i++){
if(arr[0][i]==x+1) sum+=arr[1][i];
}

cout<<sum<<endl;
return 0;
}

Q28. TOGGLE COLUMN


/*
https://www.geeksforgeeks.org/samsung-interview-experience-on-campus-for-r-d-noida/

A binary matrix of nxm was given, you have to toggle any column k number of times so that you can get the
maximum
number of rows having all 1’s.

for eg, n=3, m=3,

100

101

100

if k=2, then we will toggle column 2 and 3 once and we will get rows 1 and 3 with 1 1 1 and 1 1 1 i.e. all 1’s so
answer is 2 as there are 2 rows with all 1’s.

if k=3, then we will toggle column 2 thrice and we will get row 2 with 1 1 1 i.e. all 1’s so answer is 1 as there
is 1 row with all 1’s.
*/

#include<iostream>

using namespace std;


int grid[100][100];
int temp[100][100];
int maxi=-1;

/* restores original given matrix*/


void restore(int grid[][100],int r,int c){

for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
grid[i][j]=temp[i][j];
}
}
}

/* calculates energy*/
int caleng(int grid[][100], int r, int c){
int allone=0,eng=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(grid[i][j]==1){
allone++;
}
if(allone==c){
eng++;
}
}
allone=0;
}
return eng;
}

/* flips the column*/


void flip(int grid[][100],int r,int c,int k){
for(int i=0;i<r;i++){
if(grid[i][k]==1){
grid[i][k]=0;
}
else if(grid[i][k]==0){
grid[i][k]=1;
}
}
}

void combinationUtil(int arr[], int data[], int start, int end, int index, int r,int row,int col){
if (index == r){
for (int j = 0; j < r; j++){
flip(grid,row,col,data[j]);
}

if(maxi < caleng(grid,row,col)){


maxi = caleng(grid,row,col);
}

restore(grid,row,col);
return;
}

for (int i = start; i <= end && end - i + 1 >= r - index; i++){
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r,row,col);
}
}

void printCombination(int arr[], int n, int r,int row,int col) {


int data[r];
combinationUtil(arr, data, 0, n-1, 0, r,row,col);
}

int main(){
int t=0;
cin>>t;
int testcase=0;
while(t--){
testcase++;

int c,r=0;
cin>>r>>c;
int s=0;
cin>>s;
int arr[c];
for(int j=0;j<c;j++){
arr[j]=j;
}

for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cin>>grid[i][j];
temp[i][j]=grid[i][j];
}
}

maxi=caleng(temp,r,c); // if initial energy is max so this is corner case ......

if(s%2==0&&s>=c){
for(int i=2;i<=c;i=i+2){
printCombination(arr, c, i,r,c);
restore(grid,r,c);
}
}

// if flips are even and flips are greater than colums then check for all columns....
if(s%2!=0&&s>=c){
for(int i=1;i<=c;i=i+2){
printCombination(arr, c, i,r,c);
restore(grid,r,c);
}
}

// if flips are odd and flips are greater than colums then check for all columns....
if(s%2==0&&s<c){
for(int i=2;i<=s;i=i+2){
printCombination(arr, c, i,r,c);
restore(grid,r,c);
}
}

// if flips are lessthan columns and even then we dont need to check for all combinations
with even length eg if flips are 3 and colums are 5 than we won't be checking for {1,2,3,4,5}....or if we have 2 flips we
won't be checking for {1,2,3,4} types of combinations
if(s%2!=0&&s<c){
for(int i=1;i<=s;i=i+2){
printCombination(arr, c, i,r,c);
restore(grid,r,c);
}
}
cout<<"#"<<testcase<<" "<<maxi<<endl;
maxi=-1;
}
}

/* the idea/approch behind the problem is that if we have given flips as even then only even length combination of
flips will give max ans
for eg I have 50 filps and 5 columns then even size combinations are {1,2},{2,3},{3,4},{4,5},{1,3} and so on here length
of combination is 2 similarly check for combination length 4 and no need to check for 6 length combination becoz we
have only 5 columns
{1,2,3,4} is one of the combination that we need to check if we will check for all combinations like {1},{2} and so on all
possible combinations including odd length combinations we will encounter TLE
similarly if flips are odd we have to check for odd size combination length({1,2,3},{1},{2},{3}..... and so on ) this isn't
exactly bruteforce but kindoff this method won't lead to TLE thats for sure.here combinations lisited above are the
places where we have to flip column

<----------------------------------------HOPE THIS WILL HELP YOU FOR ALL THE SOLUTIONS TO SAMSUNG PROBLEMS
LIKE ENDOSCOPE WORMHOLES types AND MANY MORE DO LET ME KNOW--------------------------------------->

*/

Q29. WORMHOLE DFS


/*
There is one spaceship. X and Y co-odinate of source of spaceship and destination spaceship is given.
There are N number of warmholes; each warmhole has 5 values. First 2 values are starting co-ordinate
of warmhole and after that value no. 3 and 4 represents ending co-ordinate of warmhole and last 5th
value is represents cost to pass through this warmhole. Now these warmholes are bi-directional. Now
the to go from (x1,y1) to (x2,y2) is abs(x1-x2)+abs(y1-y2). The main problem here is to find minimum
distance to reach spaceship from source to destination co-ordinate using any number of warm-hole.
It is ok if you wont use any warmhole.
*/
#include <iostream>
#include <climits>
using namespace std;

int ANS = INT_MAX, n, temp = 0;


int w[35][5];
int mask[35];

int abs(int i){


return (i>=0) ? i : -1*i;
}

int min(int x, int y){


return (x>=y) ? y : x;
}

int dist(int sX, int sY, int tX, int tY){


return abs(sX-tX) + abs(sY-tY);
}
void wormhole(int sX, int sY, int tX, int tY, int value){
ANS = min(ANS, dist(sX, sY, tX, tY) + value);

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


if(mask[i] == 0){
mask[i] = 1;

/* Choose lower end of wormhole */


temp = dist(sX, sY, w[i][0], w[i][1]) + w[i][4] + value;
wormhole(w[i][2], w[i][3], tX, tY, temp);

/* Choose upper end of wormhole */


temp = dist(sX, sY, w[i][2], w[i][3]) + w[i][4] + value;
wormhole(w[i][0], w[i][1], tX, tY, temp);

mask[i] = 0;
}
}
}

int main() {
int t, sX, sY, tX, tY;
cin >> t;
while(t--){
ANS = INT_MAX;
cin >> n;
cin >> sX >> sY >> tX >> tY;
for(int i=0; i<n; i++){
mask[i] = 0;
for(int j=0; j<5; j++){
cin >> w[i][j];
}
}

wormhole(sX, sY, tX, tY, 0);


cout << ANS << endl;
}
return 0;
}

// #include<iostream>
// using namespace std;

// int n, a[2001][6];

// int min(int x , int y){


// return(x>=y) ? y : x ;
// }

// int abs(int x){


// return (x > 0) ? x : -x ;
// }
// int dist(int x1 , int y1 , int x2 , int y2){
// return abs(x2-x1) + abs(y2 - y1);
// }

// void wormhole ( int x1 , int y1 , bool *visited , int &ans , int val ) {
// if ( x1 == a[n+1][0] && y1 == a[n+1][1] ){
// ans = min ( ans , val);
// return ;
// }

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


// if (!visited[i]) {
// visited[i] = true ;

// //entry
// wormhole ( a[i][2] , a[i][3] , visited , ans , val + dist ( x1 , y1 , a[i][0] , a[i][1] ) + a[i][4]);

// //exit
// wormhole ( a[i][0] , a[i][1] , visited , ans , val + dist ( x1 , y1 , a[i][2] , a[i][3] ) + a[i][4]);

// visited[i] = false;
// }
// }
// }

// int main(){
// int t;cin >> t ;
// for (int i = 1; i <= t ; i++){
// cin >> n;
// int sx, sy, dx,dy;
// cin>>sx>>sy>>dx>>dy;

// a[0][0] = sx ; a[0][1] = sy ; a[0][2] = sx ; a[0][3] = sy ; a[0][4] = 0 ;

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


// cin >> a[i][0] >> a[i][1] >> a[i][2] >> a[i][3] >> a[i][4];
// }

// a[n+1][0] = dx ; a[n+1][1] = dy ; a[n+1][2] = dx ; a[n+1][3] = dy ; a[n+1][4] = 0 ;

// int ans ;
// bool visited[n+2] = { false };

// ans = dist (a[0][0] , a[0][1] , a[n+1][0] , a[n+1][1]);


// visited[0] = true ;

// wormhole(sx ,sy , visited , ans , 0);

// cout << "#" << i << " : " << ans << endl;
// }
// return 0;
// }

Q30. WORMHOLE FLYOD WARSHALL


#include<iostream>
using namespace std;
struct node{
int x, y;
};

int abs(int x){


return (x<0) ? -x : x;
}

int finddist(struct node *first,struct node *second){


int dstx = abs(first->x - second->x);
int dsty = abs(first->y - second->y);
return dstx + dsty;
}

int main(){
int test;
cin >> test;
for(int t=1;t<=test;t++){
int warmholes;
cin>>warmholes;

/* Initialise Code */
int nodes = 2 * warmholes + 2;
struct node *location[nodes];

int cost[nodes][nodes];
for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
cost[i][j]=-1;
}
}

//source
int sx, sy;
cin>>sx>>sy;
struct node *src=new struct node;
src->x=sx;
src->y=sy;
location[0]=src;

//destination
int dox,doy;
cin>>dox>>doy;
struct node *temp=new node;
temp->x=dox;
temp->y=doy;
location[nodes-1]=temp;

//warmhole
for(int i=0;i<warmholes;i++){
int six, siy;
cin>>six>>siy;
struct node *temp=new node;
temp->x=six;
temp->y=siy;

int dix,diy;
cin>>dix>>diy;
struct node *temp1=new node;
temp1->x=dix;
temp1->y=diy;

int w;
cin>>w;

location[2*i+1]=temp;
location[2*i+2]=temp1;
cost[2*i+1][2*i+2]=w;
cost[2*i+2][2*i+1]=w;
}

// Initialise cost matrix


for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
if(cost[i][j] == -1){
cost[i][j] = finddist(location[i],location[j]);
}
}
}

// Floyd Warshall
for(int k=0;k<nodes;k++){
for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
if(i==k||j==k)
continue;
cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);
}
}
}

cout << "#" << t << " : " << cost[0][nodes-1] << "\n";
}
return 0;
}

Q31.
Given below are the raw materials quantities and their respective selling price(if sold as raw).

D --> No of CPUs
E --> No of memory chips
F --> No of boards
d --> Selling price of CPU
e --> Selling price of Memory chips
We are given N Computer configurations like below :
Di, Ei, Fi, SPi, which are the CPU, Chips, Boards and one unit selling price for ith computer respectively.
Our task is to maximize the final cost.
Constraints:
1. Can use at Max 3 different Configurations
2. We can use 1 configuration multiple times
3. Remaining Inventories can be sold on its selling price

Input:
T --> Number of test cases.
D E F d e --> Inventories
N --> Total Configuration Count
Di Ei Fi SPi
...
Dn En Fn SPn

1<=T<=10
1<= D, E, F <= 100
1<= d, e <=100000
1<=N<=8

Output:
First Line print the Case #testCaseNumber
Second Line Print Maximum Cost per test case in each line.

Sample Input:
1 --> Total Test Case
10 10 10 2 1 --> D E F d e
1 --> PC Configuration Count
1 2 2 3 --> D1 E1 F1 SP1

Sample Output:
Case #1
30

Solution:

#include<iostream>

using namespace std;

#define rep(i,a,n) for(int i =a; i < n; i++)


#define repe(i,a,n) for(int i =a; i <= n; i++)

int D,E,F,d,e;
int config;
int answer = 0;

struct configuration
{
int D,E,F,SPi;
};
configuration m[9];

void solve(int index, int counta, int D, int E, int F, int cost )
{

if(index >= config || counta == 3)


{
cost += D*d + E*e;
if(cost > answer)
answer = cost;
return;
}
solve(index + 1, counta, D,E,F,cost);

int i = 1;

while(true)
{
if( D - m[index].D*i >= 0 && E - m[index].E*i >=0 && F - m[index].F*i >= 0 )
{
solve(index+1,counta+1,D- m[index].D *i,E - m[index].E *i,F- m[index].F*i, cost+ m[index].SPi * i);
++i;
}
else
{
break;
}
}
return;

int main()
{
int t;
cin >> t;
repe(_cases,1,t)
{

answer = 0;
cin >> D >> E >> F >> d >> e;

cin >> config;

rep(i,0,config)
{
cin >> m[i].D >> m[i].E >> m[i].F >> m[i].SPi;
}
solve(0,0,D,E,F,0);
cout << "Case #"<<_cases << "\n" << answer <<"\n";

return 0;
}

Q32.
You want to cut a piece of paper by a certain fixed rule to make some pieces of white or
blue colored square paper with various sizes.

If the size of the entire paper is N×N (N = 2^K; 1 <= K <= 7; K = natural number), the cutting rules
are as below.

‘If the entire piece of paper is not colored the same, cut the middle part horizontally and vertically
to divide it into the same sized four pieces of paper,
(N/2)×(N/2), as with I, II, III, IV in < FIG. 2 >.

For each I, II, III and IV, cut and divide again in the same way if one entire piece of paper
is not colored the same, and make them into the same sized four pieces of paper. Continue until each and
every piece of paper has only one color of white or blue.’

When you finish, < FIG. 3 > shows the first division of < FIG. 1 > and < FIG. 4 >
shows the final version of 9 pieces of white paper and 7 pieces of blue paper of various sizes.

If the length of an edge of the first given piece of paper, N, and


the color information (white or blue) inside each square are given, create a calculation program
that assesses how many white/blue pieces of paper are.

Time limit: 1 second (java: 2 seconds)

[Input]

Input may include many test cases. The number of test cases, T, is given on the first line of input and then the
amount of T of test cases is given in a line. (T <= 30)
The length of an edge of the first given piece of paper, N, is given for the first line of each test case.
From the next line through to the amount of N lines, the color information is given separately as blanks. 0 indicates
white and 1 indicates blue.

[Output]

For each test case, you should print "Case #T" in the first line where T means the case number.

For each test case, you should output the number of white pieces of paper and blue pieces of paper separately as
blanks on the first line of each test case.

[I/O Example]
Input
2
8
11000011
11000011
00001100
00001100
10001111
01001111
00111111
00111111
16
1001000000110111
1101011000000000
0000101111001001
1100100100101110
0111001100100111
1011000101010011
1111110011111000
1101010010111001
1111110010110110
1001110000111100
1001111000110101
1110110011111101
1111110000111100
1111110111111100
1100000011011000
1100110001111000

Output

Case #1
97

Case #2
88 99

Solution :
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define debug(x) cout << '>' << #x << ':' << x << endl;
const int maxn = 129;
int white = 0, blue = 0;

bool checkSame(bool arr[maxn][maxn], int sti, int stj, int size)


{
bool color = arr[sti][stj];
for(int i = sti; i < sti + size; i++){
for(int j = stj; j < stj + size; j++){
if(arr[i][j] != color){
return false;
}
}
}
return true;
}
void solve(bool arr[maxn][maxn], int size, int sti, int stj)
{
bool same = checkSame(arr, sti, stj, size);

if(!same){
solve(arr, size / 2, sti, stj);
solve(arr, size / 2, sti + size/2, stj);
solve(arr, size / 2, sti, stj + size/2);
solve(arr, size / 2, sti + size/2, stj + size/2);
}
else{
(arr[sti][stj]) ? ++blue : ++white ;
}
}

int main()
{
int test ;
cin >> test ;
for(int l = 1; l <= test; l++){
white = 0;
blue = 0;
int size ;
cin >> size;
bool arr[maxn][maxn];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
cin >> arr[i][j] ;
}
}
solve(arr, size, 0, 0);
cout << "Case #" << l << endl;
cout << white << " " << blue << endl;
}
return 0;
}
// optimized approach using prefix sum of matrix

#include <iostream>
using namespace std;
const int maxn = 129;
int white = 0, blue = 0;
void solve(int arr[maxn][maxn], int size, int si,int sj)
{
if( size == 0)
return;
int sum = arr[size + si - 1][size + sj - 1];
if(sj - 1 >= 0)
sum -= arr[size + si - 1][sj - 1];
if(si - 1 >= 0)
sum -= arr[si - 1][sj + size - 1];
if( si - 1 >= 0 && sj - 1 >= 0)
sum += arr[si - 1][sj - 1];
if(si == 4 && sj == 1)
cout<<sum<<endl;
if(sum == 0)
{
// cout<<si<<"white"<<sj<<" "<<size<<" "<<white<<endl;
white++;
return;
}
if(sum == size * size)
{
//cout<<si<<"blue"<<sj<<" "<<size<<" "<<blue<<endl;
blue++;
return;
}
solve(arr, size / 2, si, sj);
solve(arr, size / 2, si + size/2, sj);
solve(arr, size / 2, si, sj + size/2);
solve(arr, size / 2, si + size / 2, sj + size / 2);
}
int main() {
int test ;
cin >> test ;
for(int l = 1; l <= test; l++){
white = 0;
blue = 0;
int size ;
cin >> size;
int arr[maxn][maxn];
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
int a;
cin>>a;
if( i == 0 && j == 0)
arr[i][j] = a;
else if( i == 0)
arr[i][j] = a + arr[i][j - 1];
else if( j == 0)
arr[i][j] = a + arr[i - 1][j];
else
arr[i][j] = a + arr[i - 1][j] + arr[i][j - 1] - arr[i - 1][j - 1];
}
}
solve(arr, size, 0, 0);
cout << "Case #" << l << endl;
cout << white << " " << blue << endl;
}
return 0;
}

You might also like