Samsung

You might also like

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

DFS

#include<iostream>
using namespace std;

struct node{
int data;
struct node *next;
};

void insert(struct node **head, int data){


struct node *temp=(struct node *)malloc(sizeof(struct node));
if(*head==NULL){
*head=temp;
temp->data=data;
temp->next=NULL;
}else{
temp->data=data;
temp->next=(*head);
*head=temp;
}
}

void dfs(struct node **a, bool *vis, int s){


vis[s]=true;
cout << s << " ";

struct node *temp=a[s];


while(temp){
if(!vis[temp->data])
dfs(a,vis,temp->data);
temp=temp->next;
}
}

int main(){
int t;
cin >> t;

while(t--){
int n, e;
cin >> n >> e;

struct node *a[n];


for(int i=0; i<n; i++)
a[i]=NULL;

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


int u, v;
cin >> u >> v;
insert(&a[u],v);
}

bool vis[n];
for(int i=0; i<n; i++)
vis[i]=false;

dfs(a,vis,0);
cout << endl;
}
}

Level Order Traversal of Tree


struct qnode{
struct Node *data;
struct qnode *next;
};

void push(struct qnode **head, struct qnode **end, struct Node *data){
struct qnode *temp=(struct qnode *)malloc(sizeof(struct qnode));
if(*head==NULL){
*head=temp;
temp->data=data;
temp->next=NULL;
*end=*head;
}else{
(*end)->next=temp;
*end=temp;
temp->data=data;
temp->next=NULL;
}
}

void pop(struct qnode **head){


struct qnode *temp=*head;
*head=(*head)->next;
free(temp);
}

struct Node *front(struct qnode *head){


return head->data;
}

void levelOrder(Node* node){


struct qnode *q=NULL;
struct qnode *end=NULL;

push(&q,&end,node);
while(q){
struct Node *temp=front(q);
pop(&q);

cout << temp->data << " ";

if(temp->left)
push(&q,&end,temp->left);
if(temp->right)
push(&q,&end,temp->right);
}
}

Dijktras (Adjacency Matrix)


int minInd(int *dist, bool *vis, int V){
int ind=0, min=1000000;
for(int i=0; i<V; i++){
if(dist[i]<min && !vis[i]){
min=dist[i];
ind=i;
}
}
return ind;
}

void dijkstra(vector<vector<int>> graph, int src, int V){


bool vis[V];
for(int i=0; i<V; i++)
vis[i]=false;

int dist[V];
for(int i=0; i<V; i++)
dist[i]=1000000;

dist[src]=0;
for(int i=0; i<V; i++){
int u=minInd(dist,vis,V);
vis[u]=true;
for(int v=0; v<V; v++){
if(graph[u][v] && !vis[v] && dist[v]>dist[u]+graph[u][v])
dist[v]=dist[u]+graph[u][v];
}
}

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


cout << dist[i] << " ";
}

Find whether path exists


Given a N X N matrix (M) filled with 1, 0, 2, 3. The task is to find
whether there is a path possible from source to destination, while
traversing through blank cells only. You can traverse up, down, right and
left.

 A value of cell 1 means Source.


 A value of cell 2 means Destination.
 A value of cell 3 means Blank cell.
 A value of cell 0 means Blank Wall.

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

struct node{
int sx;
int sy;
struct node *next;
};

void push(struct node **head, struct node **end, int sx, int sy){
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->sx=sx;
temp->sy=sy;
temp->next=NULL;
if(*head==NULL){
*head=temp;
*end=temp;
}else{
(*end)->next=temp;
*end=temp;
}
}

void pop(struct node **head){


struct node *temp=*head;
*head=(*head)->next;
free(temp);
}

bool isValid(int x, int y, int n){


return (x>=0 && x<n && y>=0 && y<n);
}

int bfs(int a[MAX][MAX], int sx, int sy, int dx, int dy, int n){
bool vis[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
vis[i][j]=false;

struct node *q=NULL;


struct node *end=NULL;

vis[sx][sy]=true;
push(&q,&end,sx,sy);
while(q){
int x=q->sx;
int y=q->sy;
pop(&q);

if(x==dx && y==dy)


return 1;

int row[]={1,-1,0,0};
int col[]={0,0,1,-1};
for(int i=0; i<4; i++){
int u=x+row[i];
int v=y+col[i];
if(isValid(u,v,n) && !vis[u][v] && (a[u][v]==3 || a[u][v]==2)){
vis[u][v]=true;
push(&q,&end,u,v);
}
}
}

return 0;
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;
int a[MAX][MAX];
int sx, sy, dx, dy;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> a[i][j];
if(a[i][j]==1){
sx=i;
sy=j;
}else if(a[i][j]==2){
dx=i;
dy=j;
}
}
}

cout << bfs(a,sx,sy,dx,dy,n) << endl;

}
return 0;
}

Topological Sort
struct node{
int data;
struct node *next;
};

void push(struct node **head, int data){


struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
if(*head==NULL){
*head=temp;
temp->next=NULL;
}else{
temp->next=*head;
*head=temp;
}
}

void pop(struct node **head){


struct node *temp=*head;
*head=(*head)->next;
free(temp);
}

void dfs(vector<int> a[], struct node **s, bool *vis, int src){
vis[src]=true;

vector<int> :: iterator i;
for(i=a[src].begin(); i!=a[src].end(); i++)
if(!vis[*i])
dfs(a,s,vis,*i);
push(s,src);
}

int* topoSort(int n, vector<int> a[])


{
bool vis[n];
for(int i=0; i<n; i++)
vis[i]=false;

struct node *s=NULL;

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


if(!vis[i])
dfs(a,&s,vis,i);
}

int *ans = new int[n];


for(int i=0; i<n; i++){
ans[i]=s->data;
pop(&s);
}
return ans;
}

Factorial of Big Number


#include<iostream>
using namespace std;

int multiply(int *res, int x, int size){


int carry=0;
for(int i=0; i<size; i++){
int pro=res[i]*x+carry;
res[i]=pro%10;
carry=pro/10;
}

while(carry){
res[size]=carry%10;
carry=carry/10;
size++;
}

return size;
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int res[3000];
res[0]=1;
int size=1;
for(int i=2; i<=n; i++)
size=multiply(res,i,size);

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


cout << res[i];
cout << endl;
}
return 0;
}
Left View of Tree
struct node{
struct Node *data;
struct node *next;
};

void push(struct node **head, struct node **end, struct Node *data){
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->next=NULL;
if(*head==NULL){
*head=temp;
*end=temp;
}else{
(*end)->next=temp;
*end=temp;
}
}

void pop(struct node **head){


struct node *temp=*head;
(*head)=(*head)->next;
free(temp);
}

void leftView(Node *root){


struct node *q=NULL;
struct node *end=NULL;
push(&q,&end,root);
push(&q,&end,NULL);

int flag=1;
while(q){
struct Node *temp=q->data;
pop(&q);

if(temp==NULL){
if(q)
push(&q,&end,NULL);
flag=1;
}else{
if(flag==1){
cout << temp->data << " ";
flag=0;
}

if(temp->left)
push(&q,&end,temp->left);
if(temp->right)
push(&q,&end,temp->right);
}
}
}
Minimum Cost Path (dijktras using priority queue)

#include<iostream>
using namespace std;

struct node{
int cost;
int x;
int y;
};

struct heap{
int size;
struct node a[1000];
};

struct heap *create(int size, int cost, int x, int y){


struct heap *q=(struct heap *)malloc(sizeof(struct heap));
q->size=size;
(q->a[0]).cost=cost;
(q->a[0]).x=x;
(q->a[0]).y=y;

return q;
}

int leftchild(struct heap *q, int i){


int left=(2*i)+1;
if(left<q->size)
return left;
return -1;
}

int rightchild(struct heap *q, int i){


int right=(2*i)+2;
if(right<q->size)
return right;
return -1;
}

int parent(struct heap *q, int i){


if(i<=0||i>q->size) return -1;
return (i-1)/2;
}

void insert(struct heap *q, int cost, int x, int y){


(q->size)++;
int i=q->size-1;
(q->a[i]).cost=cost;
(q->a[i]).x=x;
(q->a[i]).y=y;

while(i>=0 && (q->a[(i-1)/2]).cost>(q->a[i]).cost){


struct node temp;
temp=q->a[(i-1)/2];
q->a[(i-1)/2]=q->a[i];
q->a[i]=temp;
i=(i-1)/2;
}
}
void heapify(struct heap *q, int i){
int left=leftchild(q,i);
int right=rightchild(q,i);

int min=i;
if(left!=-1 && (q->a[i]).cost>(q->a[left]).cost)
min=left;
if(right!=-1 && (q->a[min]).cost>(q->a[right]).cost)
min=right;

if(min!=i){
struct node temp=q->a[i];
q->a[i]=q->a[min];
q->a[min]=temp;
heapify(q,min);
}
}

struct node extractmin(struct heap *q){


struct node temp=q->a[0];
q->a[0]=q->a[q->size-1];
(q->size)--;
heapify(q,0);
return temp;
}

bool isvalid(int x, int y, int n){


return (x>=0 && x<n && y>=0 && y<n);
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int a[n][n];
bool vis[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++){
cin >> a[i][j];
vis[i][j]=false;
}

int ans=0;
struct heap *q=create(1,a[0][0],0,0);
while(q){
struct node temp=extractmin(q);
int cost=temp.cost;
int x=temp.x;
int y=temp.y;

if(vis[x][y])
continue;

vis[x][y]=true;
if(x==n-1 && y==n-1){
ans=cost;
break;
}

int row[]={1,-1,0,0};
int col[]={0,0,1,-1};
for(int i=0; i<4; i++){
int u=x+row[i];
int v=y+col[i];
if(isvalid(u,v,n) && !vis[u][v]){
insert(q,cost+a[u][v],u,v);
}
}
}

cout << ans << endl;


}
return 0;
}

Delete Node in BST


Node *leftmax(Node *root){
if(root==NULL)
return NULL;

if(!root->right)
return root;

return leftmax(root->right);
}
Node *del(struct Node *root, int x){
if(root==NULL)
return NULL;

if(x==root->data){
if(!root->left && !root->right){
return NULL;
}else if(root->left && root->right){
struct Node *temp=leftmax(root->left);
root->data=temp->data;
root->left=del(root->left,temp->data);
return root;
}else if(root->left){
return root->left;
}else if(root->right){
return root->right;
}
}

root->left=del(root->left,x);
root->right=del(root->right,x);

return root;
}

Node *deleteNode(Node *root, int x){


return del(root,x);
}
Node at given distance in Binary Tree
void printkdistanceNodeDown(node *root, int k){
if(root==NULL)
return;

if(k==0){
cout << root->data << " ";
return;
}

printkdistanceNodeDown(root->left,k-1);
printkdistanceNodeDown(root->right,k-1);
}

void print(node *root, node *target, int &k, int &flag){


if(root==NULL)
return;

if(root==target){
flag=1;
printkdistanceNodeDown(target,k);
return;
}

if(flag==0)
print(root->left,target,k,flag);
if(flag==1){
k--;
if(k==0)
cout << root->data << " ";
else
printkdistanceNodeDown(root->right,k-1);
return;
}

if(flag==0)
print(root->right,target,k,flag);
if(flag==1){
k--;
if(k==0)
cout << root->data << " ";
else
printkdistanceNodeDown(root->left,k-1);
return;
}
}

int printkdistanceNode(node* root, node* target , int k){


int flag=0;
print(root,target,k,flag);
}
Top View of Tree
struct que{
int data;
struct Node *qnode;
struct que *next;
};

void push(struct que **head, struct que **end, int data, struct Node
*qnode){
struct que *temp=(struct que *)malloc(sizeof(struct que));
temp->data=data;
temp->qnode=qnode;
temp->next=NULL;

if(*head==NULL){
*head=temp;
*end=temp;
}else{
(*end)->next=temp;
*end=temp;
}
}

void pop(struct que **head){


struct que *temp=*head;
*head=(*head)->next;
free(temp);
}

void topView(struct Node *root){


int neg[101];
int pos[101];
for(int i=0; i<101; i++){
neg[i]=-1;
pos[i]=-1;
}

int left=0, right=0;


struct que *q=NULL;
struct que *end=NULL;
push(&q,&end,0,root);
while(q){
int dist=q->data;
struct Node *temp=q->qnode;
pop(&q);

if(dist<=0 && neg[-dist]==-1){


neg[-dist]=temp->data;
if(-dist>left)
left=-dist;
}
else if(dist>0 && pos[dist]==-1){
pos[dist]=temp->data;
if(dist>right)
right=dist;
}

if(temp->left)
push(&q,&end,dist-1,temp->left);
if(temp->right)
push(&q,&end,dist+1,temp->right);
}

for(int i=left; i>=0; i--)


cout << neg[i] << " ";
for(int i=1; i<=right; i++)
cout << pos[i] << " ";
}

Manacher Algorithm
#include<iostream>
using namespace std;

int main(){
int t;
cin >> t;

while(t--){
string str;
cin >> str;

string s="$";
for(int i=0; str[i]!='\0'; i++)
s=s+"#"+str[i];
s=s+"#@";

int p[s.length()]={0};
int c=0, r=0;
for(int i=0; i<s.length(); i++){
int mirr=2*c-i;

if(i<r)
p[i]=min(p[mirr],r-i);

while(s[i+(p[i]+1)]==s[i-(p[i]+1)])
p[i]++;

if(i+p[i]>r){
c=i;
r=p[i]+i;
}
}

int max=0, ind=0;


for(int i=0; i<s.length(); i++){
if(p[i]>max){
max=p[i];
ind=i;
}
}

string ans="";
for(int i=ind-max+1; i<ind; i=i+2)
ans+=s[i];
int x=0;
if(max%2==0)
x=1;
for(int i=ind+x; i<=ind+max-1; i=i+2)
ans=ans+s[i];

cout << ans << endl;


}
return 0;
}

Largest BST
struct node{
bool is;
int size;
int max;
int min;
};

struct node largest(Node *root, int &max){


if(root==NULL)
return {true,0,-10000000,10000000};

if(!root->left && !root->right)


return {true,1,root->data,root->data};

struct node left=largest(root->left,max);


struct node right=largest(root->right,max);

if(left.is && right.is && root->data>left.max && root->data<right.min){


if(max<left.size+right.size+1)
max=left.size+right.size+1;
struct node info;
info.size=left.size+right.size+1;
info.is=true;
if(!root->left)
info.min=root->data;
else
info.min=left.min;

if(!root->right)
info.max=root->data;
else
info.max=right.max;

return info;
}
return {false,1,-10000000,10000000};

int largestBst(Node *root){


if(root==NULL)
return 0;

int max=1;
largest(root,max);

return max;
}
No. of Turns
struct Node *lca(Node *root, int first, int second){
if(root==NULL)
return NULL;

if(root->key==first || root->key==second)
return root;

struct Node *left=lca(root->left,first,second);


struct Node *right=lca(root->right,first,second);

if(left && right)


return root;

return left?left:right;
}

void calc(struct Node *root, int first, int &turn, int cnt, int side){
if(root==NULL)
return;

if(root->key==first){
turn=cnt;
return;
}

if(side==0){
calc(root->left,first,turn,0,1);
calc(root->right,first,turn,0,2);
}else if(side==1){
calc(root->left,first,turn,cnt,1);
calc(root->right,first,turn,cnt+1,2);
}else if(side==2){
calc(root->left,first,turn,cnt+1,1);
calc(root->right,first,turn,cnt,2);
}
}

int NumberOFTurn(struct Node* root, int first, int second){


struct Node *com=lca(root,first,second);

int left=0;
calc(com,first,left,0,0);
int right=0;
calc(com,second,right,0,0);

if(com->key==first || com->key==second)
return left+right;
return left+right+1;
}

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

struct node{
int freq;
char ch;
struct node *left;
struct node *right;
};

struct cmp{
bool operator()( node *a, node *b) {
return a->freq>b->freq;
}
};

void preorder(struct node *root, string s){


if(root==NULL)
return;

if(!root->left && !root->right){


cout << s << " ";
return;
}

preorder(root->left,s+"0");
preorder(root->right,s+"1");
}

int main(){
int t;
cin >> t;

while(t--){
string s;
cin >> s;

priority_queue<struct node *, vector<struct node *>, cmp> q;

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


int freq;
cin >> freq;
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->freq=freq;
temp->ch=s[i];
temp->left=NULL;
temp->right=NULL;
q.push(temp);
}

struct node *huff=NULL;


while(!q.empty()){
struct node *first=q.top();
q.pop();
if(q.empty()){
huff=first;
break;
}
struct node *second=q.top();
q.pop();

struct node *temp=(struct node *)malloc(sizeof(struct node));


temp->freq=first->freq+second->freq;
temp->ch='$';
temp->left=first;
temp->right=second;
q.push(temp);
}

preorder(huff,"");
cout << endl;
}
return 0;
}

Boundary Traversal of Binary Tree


void printleft(Node *root, int flag){
if(root==NULL)
return;

if(!root->left && !root->right)


return;

cout << root->data << " ";


printleft(root->left,1);
if(!root->left && flag==1)
printleft(root->right,1);
}

void printbottom(Node *root){


if(root==NULL)
return;

if(!root->left && !root->right){


cout << root->data << " ";
return;
}

printbottom(root->left);
printbottom(root->right);
}

void printright(Node *root, int flag){


if(root==NULL)
return;

if(!root->left && !root->right)


return;

printright(root->right,1);
if(!root->right && flag==1)
printright(root->left,1);
if(flag==1)
cout << root->data << " ";
}

void printBoundary(Node *root){


printleft(root,0);
printbottom(root);
printright(root,0);
}
Tower of Hanoi
#include<iostream>
using namespace std;

void print(int n, int from, int to, int aux, int &cnt){
if(n==1){
cout << "move disk 1 from rod " << from << " to rod " << to
<<endl;
cnt++;
return;
}
print(n-1,from,aux,to,cnt);
cout << "move disk " << n << " from rod " << from << " to rod " << to
<< endl;
cnt++;
print(n-1,aux,to,from,cnt);
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int cnt=0;
print(n,1,3,2,cnt);
cout << cnt << endl;
}
return 0;
}

Multiplication of two strings


string multiplyStrings(string s1, string s2) {
if(s1.length()==0 || s2.length()==0)
return "0";

int x=0, y=0;


if(s1[0]=='-')
x=1;
if(s2[0]=='-')
y=1;

int a[s1.length()+s2.length()]={0};
int n1=0, n2=0;
for(int i=s1.length()-1; i>=x; i--){
n2=0;
int carry=0;
for(int j=s2.length()-1; j>=y; j--){
int num=((s1[i]-'0')*(s2[j]-'0'))+a[n1+n2]+carry;
a[n1+n2]=num%10;
carry=num/10;
n2++;
}
if(carry>0)
a[n1+n2]=a[n1+n2]+carry;
n1++;
}

int i=s1.length()+s2.length()-1;
while(i>=0 && a[i]==0)
i--;

if(i==-1)
return "0";

string s="";
while(i>=0){
s=s+to_string(a[i]);
i--;
}

if((x==1&&y!=1)||(x!=1&&y==1))
s='-'+s;
return s;
}

Find Number in bitonic array


#include<iostream>
using namespace std;

int binarySearch(int arr[], int low, int high, int key) {


if (high < low)
return -1;

int mid = (low + high)/2; /*low + (high - low)/2;*/


if (key == arr[mid])
return mid;

if (key > arr[mid])


return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid -1), key);
}

int binarySearch2(int arr[], int low, int high, int key) {


if (high < low)
return -1;

int mid = (low + high)/2; /*low + (high - low)/2;*/


if (key == arr[mid])
return mid;

if (key > arr[mid])


return binarySearch2(arr, low, mid-1, key);
return binarySearch2(arr, mid+1, high, key);
}

int findPoint(int *a, int l, int h){


if(h<l)
return -1;
if(l==h)
return h;
if(l==h-1){
if(a[l]>a[h])
return l;
return h;
}

int mid = (l+h)/2;


if(a[mid-1]<a[mid] && a[mid]>a[mid+1])
return mid;

if(a[l]>=a[mid])
return findPoint(a,l,mid-1);
return findPoint(a,mid+1,h);
}

int Search(int *a, int n, int x){


int point = findPoint(a,0,n);
if(point==-1)
return binarySearch(a,0,n-1,x);

int left=binarySearch(a,0,point,x);
int right=binarySearch2(a,point+1,n-1,x);

if(left==-1 && right==-1)


return -1;
else if(left>right)
return left;
return right;

int main()
{
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int *a = (int *)malloc(sizeof(int)*n);


for(int i=0; i<n; i++)
cin >> a[i];

int x;
cin >> x;

cout << Search(a,n,x) << endl;


}
return 0;
}

LRU Cache
struct node{
int key;
int value;
struct node *next;
};

struct que{
int size;
struct node *head;
struct node *end;
};

struct que *temp=(struct que*)malloc(sizeof(struct que));


int cnt;

LRUCache::LRUCache(int N){
cnt=0;
temp->size=N;
temp->head=NULL;
temp->end=NULL;
}

void LRUCache::set(int x, int y){


struct node *t=temp->head;
struct node *prev=NULL;

int flag=0;
while(t){
if(t->key==x){
flag=1;
break;
}
prev=t;
t=t->next;
}

if(flag==1){
if(prev==NULL){
struct node *a=t;
temp->head=temp->head->next;
free(a);
}else{
prev->next=t->next;
if(prev->next==NULL)
temp->end=prev;
free(t);
}

struct node *c=(struct node *)malloc(sizeof(struct node));


c->key=x;
c->value=y;
c->next=NULL;
if(temp->head==NULL){
temp->head=c;
temp->end=c;
}else{
temp->end->next=c;
temp->end=c;
}
}else{
if(cnt==temp->size){
struct node *a=temp->head;
temp->head=temp->head->next;
free(a);
cnt--;
}
struct node *b=(struct node *)malloc(sizeof(struct node));
b->key=x;
b->value=y;
b->next=NULL;
if(temp->head==NULL){
temp->head=b;
temp->end=b;
}else{
temp->end->next=b;
temp->end=b;
}
cnt++;
}
}

int LRUCache::get(int x){


struct node *t=temp->head;
struct node *prev=NULL;

int flag=0;
while(t){
if(t->key==x){
flag=1;
break;
}
prev=t;
t=t->next;
}

if(flag==0)
return -1;

int value=t->value;
if(prev==NULL){
struct node *a=temp->head;
temp->head=temp->head->next;
free(a);
}else{
prev->next=t->next;
if(prev->next==NULL)
temp->end=prev;
free(t);
}

struct node *b=(struct node *)malloc(sizeof(struct node));


b->key=x;
b->value=value;
b->next=NULL;
if(temp->head==NULL){
temp->head=b;
temp->end=b;
}else{
temp->end->next=b;
temp->end=b;
}
return value;
}
Men's restroom problem :
It is a well-researched fact that men in a restroom generally prefer to maximize their distance from
already occupied stalls, by occupying the middle of the longest sequence of unoccupied places.

https://github.com/ifqthenp/big-java/blob/master/late-objects/06-arrays-
and-array-lists/src/main/java/p_06_16_occupy_stalls/OccupyStalls.java

Endoscope Problem
#include<bits/stdc++.h>
using namespace std;
#define MAX 1001

struct node{
int r;
int c;
int cnt;
};

bool isvalid(int x, int y, int n, int m){


return (x>=0 && x<n && y>=0 && y<m);
}

void bfs(int a[MAX][MAX], int r, int c, int n, int m, int len,


vector<vector<pair<int,int>>> dir, int &total){
bool vis[n][m];
memset(vis,false,sizeof vis);
vis[r][c]=true;

queue<struct node> q;
q.push({r,c,1});
while(!q.empty()){
struct node temp=q.front();
q.pop();

int x=temp.r;
int y=temp.c;
int cnt=temp.cnt;

if(cnt==len)
continue;

int p=a[x][y];
vector<pair<int,int>> :: iterator i;
for(i=dir[p].begin(); i!=dir[p].end(); i++){
int u=x+(*i).first;
int v=y+(*i).second;
if(isvalid(u,v,n,m) && !vis[u][v]){
if((*i).first==0 && (*i).second==1 && (a[u][v]==1 ||
a[u][v]==3 || a[u][v]==6 || a[u][v]==7)){
total++;
vis[u][v]=true;
q.push({u,v,cnt+1});
}else if((*i).first==0 && (*i).second==-1 && (a[u][v]==1 ||
a[u][v]==3 || a[u][v]==4 || a[u][v]==5)){
total++;
vis[u][v]=true;
q.push({u,v,cnt+1});
}else if((*i).first==1 && (*i).second==0 && (a[u][v]==1 ||
a[u][v]==2 || a[u][v]==4 || a[u][v]==7)){
total++;
vis[u][v]=true;
q.push({u,v,cnt+1});
}else if((*i).first==-1 && (*i).second==0 && (a[u][v]==1 ||
a[u][v]==2 || a[u][v]==5 || a[u][v]==6)){
total++;
vis[u][v]=true;
q.push({u,v,cnt+1});
}
}
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n, m, r, c, l;
cin >> n >> m >> r >> c >> l;

int a[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin >> a[i][j];

vector<vector<pair<int,int>>> dir={{{1,0},{-1,0},{0,1},{0,-1}},
{{1,0},{-1,0},{0,1},{0,-1}},
{{1,0},{-1,0}},
{{0,1},{0,-1}},
{{-1,0},{0,1}},
{{1,0},{0,1}},
{{0,-1},{1,0}},
{{-1,0},{0,-1}}};

int total=1;
if(a[r][c]==0)
total=0;
else
bfs(a,r,c,n,m,l,dir,total);

cout << total << endl;


}
}
Spaceship and Bomb
#include<iostream>
using namespace std;
#define MAX 100

bool isvalid(int x, int y, int n){


return (x>=0 && x<n && y>=0 && y<5);
}

void space(int mat[MAX][5], int x, int y, int n, int bomb, int coin, int
&max){
if(x!=n){
if(mat[x][y]==2){
if(coin>max)
max=coin;
return;
}
if(mat[x][y]==1)
coin++;
}

if(isvalid(x-1,y-1,n))
space(mat,x-1,y-1,n,bomb,coin,max);
if(isvalid(x-1,y,n))
space(mat,x-1,y,n,bomb,coin,max);
if(isvalid(x-1,y+1,n))
space(mat,x-1,y+1,n,bomb,coin,max);

if(bomb==0){

int temp[n][5];
for(int i=0; i<n; i++){
for(int j=0; j<5; j++)
temp[i][j]=mat[i][j];
}

for(int i=x-1, k=1; i>=0 && k<=5; i--,k++){


for(int j=0; j<5; j++)
if(mat[i][j]==2)
temp[i][j]=0;
}

if(isvalid(x-1,y-1,n))
space(temp,x-1,y-1,n,1,coin,max);
if(isvalid(x-1,y,n))
space(temp,x-1,y,n,1,coin,max);
if(isvalid(x-1,y+1,n))
space(temp,x-1,y+1,n,1,coin,max);
}

if(coin>max)
max=coin;
return;
}

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

int a[MAX][5];
for(int i=0; i<n; i++)
for(int j=0; j<5; j++)
cin >> a[i][j];

int max=0;
space(a,n,2,n,0,0,max);
cout << max << endl;
}
return 0;
}

Nth magical number


#include<iostream>
using namespace std;

long long int find(int n){


long long int ans=0;
long long int po=1;
while(n){
if(n&1)
ans+=po;
po=po*7;
n=n>>1;
}

return ans;
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

cout << find(n) << endl;


}
return 0;
}

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

int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}

int main(){
int t;
cin >> t;

while(t--){
string s;
cin >> s;

int i=0;
stack<char> st;
while(i<s.length()){

if(s[i]=='(')
st.push(s[i]);
else if(s[i]==')'){
while(st.top()!='('){
cout << st.top();
st.pop();
}
st.pop();
}
else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' ||
s[i]=='^'){
if(st.empty())
st.push(s[i]);
else{
while(!st.empty() && prec(s[i])<=prec(st.top())){
cout << st.top();
st.pop();
}
st.push(s[i]);
}
}else
cout << s[i];

i++;
}
while(!st.empty()){
cout << st.top();
st.pop();
}
cout << endl;

}
return 0;
}
Median in a stream
#include<bits/stdc++.h>
using namespace std;

void addNumber(int num, priority_queue<int> &lower,


priority_queue<int,vector<int>,greater<int>> &higher){
if(lower.size()==0 || num<lower.top())
lower.push(num);
else
higher.push(num);
}

void rebalance(priority_queue<int> &lower,


priority_queue<int,vector<int>,greater<int>> &higher){

if(abs(lower.size()-higher.size())>=2){
if(lower.size()>higher.size()){
higher.push(lower.top());
lower.pop();
}else{
lower.push(higher.top());
higher.pop();
}
}
}

int median(priority_queue<int> lower,


priority_queue<int,vector<int>,greater<int>> higher){
if(lower.size()==higher.size())
return (lower.top()+higher.top())/2;
else if(lower.size()>higher.size())
return lower.top();
return higher.top();
}

int main(){
int t;
cin >> t;

priority_queue<int> lower;
priority_queue<int,vector<int>,greater<int>> higher;

while(t--){
int num;
cin >> num;

addNumber(num,lower,higher);
rebalance(lower,higher);
cout << median(lower,higher) << endl;
}
return 0;
}
TSP using DP (Bitmasking)
#include<iostream>
using namespace std;
#define MAX 15
#define M 6000

long int total;

long int tsp(int a[MAX][MAX], long int dp[M][MAX], long int mask, int pos,
int n){
if(mask==total){
if(a[pos][0]==0)
return 10000000;
return a[pos][0];
}

if(dp[mask][pos]!=-1)
return dp[mask][pos];

long int ans=100000000;


for(int i=1; i<n; i++){
if((mask&(1<<i))==0){
long int newans=a[pos][i]+tsp(a,dp,mask|(1<<i),i,n);
ans=min(ans,newans);
}
}

return dp[mask][pos]=ans;
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int a[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin >> a[i][j];

long int dp[M][MAX];


for(long int i=0; i<1<<n; i++)
for(int j=0; j<n; j++)
dp[i][j]=-1;

total=(1<<n)-1;
cout << tsp(a,dp,1,0,n) << endl;
}
return 0;
}
Place the Cows
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.

#include<iostream>
using namespace std;

int partition(int *a, int low, int high){


int j=low-1;
int pivot=a[high];
for(int i=low; i<=high-1; i++){
if(a[i]<=pivot)
swap(a[i],a[++j]);
}
swap(a[j+1],a[high]);
return j+1;
}

void quicksort(int *a, int low, int high){


if(low<high){
int pivot=partition(a,low,high);
quicksort(a,low,pivot-1);
quicksort(a,pivot+1,high);
}
}

bool feasible(int *a, int high, int mid, int k){


int elements=1;
int num=a[0];
for(int i=1; i<=high; i++){
if(a[i]-num>=mid){
elements++;
num=a[i];

if(elements==k)
return true;
}
}
return false;
}

int largestmindist(int *a, int high, int k){


int left=a[0], right=a[high];
int res=-1;
while(left<right){
int mid=(left+right)/2;

if(feasible(a,high,mid,k)){
if(mid>res)
res=mid;
left=mid+1;
}else
right=mid;
}
return res;
}
int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int a[n];
for(int i=0; i<n; i++)
cin >> a[i];

int k;
cin >> k;

quicksort(a,0,n-1);

cout << largestmindist(a,n-1,k) << endl;


}
return 0;
}

Mr Kim Refrigerators

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>
using namespace std;
#define MAX 15

struct node{
int x;
int y;
};

void tsp(int a[MAX][MAX], bool *vis, int s, int v, int n, int c, int
&cost){
if(v==n){
if(c+a[s][1]<cost)
cost=c+a[s][1];
return;
}

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


if(!vis[i]){
vis[i]=true;
tsp(a,vis,i,v+1,n,c+a[s][i],cost);
vis[i]=false;
}
}
}

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

struct node inp[(n+2)];


for(int i=0; i<n+2; i++){
int u, v;
cin >> u >> v;
inp[i].x=u;
inp[i].y=v;
}

int a[MAX][MAX];
for(int i=0; i<n+2; i++){
for(int j=0; j<n+2; j++){
if(i==j)
a[i][j]=0;
else
a[i][j]=abs(inp[i].x-inp[j].x)+abs(inp[i].y-inp[j].y);
}
}

bool vis[n+2];
for(int i=0; i<n+2; i++)
vis[i]=false;

int cost=100000000;
tsp(a,vis,0,0,n,0,cost);
cout << cost << endl;
}
}

Convex HULL
#include<iostream>
using namespace std;

struct point{
int x;
int y;
};

int crossPro(point a, point b, point c){


int x1=a.x-b.x;
int x2=a.x-c.x;
int y1=a.y-b.y;
int y2=a.y-c.y;

return y2*x1-y1*x2;
}

int distance(point a, point b, point c){


int x1=a.x-b.x;
int x2=a.x-c.x;
int y1=a.y-b.y;
int y2=a.y-c.y;

return x1*x1+y1*y1-x2*x2+y2*y2;
}
bool compare(point a, point b){
return (a.x==b.x && a.y==b.y);
}

struct point *findConvexHull(struct point points[], int n, int &cnt){


struct point start=points[0];
for(int i=1; i<n; i++){
if(points[i].x<start.x)
start=points[i];
}

struct point *result=(struct point *)malloc(sizeof(struct point)*n);


result[0]=start;
cnt=1;

struct point current=start;


struct point *col=(struct point *)malloc(sizeof(struct point)*n);
int co=0;
while(1){
struct point next;
for(int i=0; i<n; i++){
if(!compare(points[i],current)){
next=points[i];
break;
}
}

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


if(compare(points[i],current) || compare(points[i],next))
continue;

int val=crossPro(current,next,points[i]);
if(val<0){
next=points[i];
co=0;
col=(struct point *)malloc(sizeof(struct point)*n);
}else if(val==0){
if(distance(current,next,points[i])<0){
col[co++]=next;
next=points[i];
}else{
col[co++]=points[i];
}
}
}

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


result[cnt++]=col[i];

if(compare(next,start))
break;

result[cnt++]=next;
current=next;
}

return result;
}

int partition(struct point result[], int low, int high){


int j=low-1;
point pivot=result[high];
for(int i=low; i<=high-1; i++){
if(result[i].x<pivot.x || (result[i].x==pivot.x &&
result[i].y<pivot.y)){
++j;
struct point temp=result[j];
result[j]=result[i];
result[i]=temp;
}
}
++j;
struct point temp=result[high];
result[high]=result[j];
result[j]=temp;

return j;
}

void quicksort(struct point result[], int low, int high){


if(low<high){
int pivot=partition(result,low,high);
quicksort(result,low,pivot-1);
quicksort(result,pivot+1,high);
}
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

struct point Points[n];


for(int i=0; i<n; i++){
int x, y;
cin >> x >> y;
Points[i].x=x;
Points[i].y=y;
}

quicksort(Points,0,n-1);

struct point points[n];


int x=0;

points[x++]=Points[0];
struct point prev=points[0];
for(int i=1; i<n; i++){
if(!compare(Points[i],prev)){
points[x++]=Points[i];
prev=Points[i];
}
}

if(x<3){
cout << "-1" << endl;
continue;
}
int cnt=0;
struct point *result=findConvexHull(points,x,cnt);

quicksort(result,0,cnt-1);

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


cout << result[i].x << " " << result[i].y;
if(i!=cnt-1)
cout << ", ";
}
cout << endl;
}
return 0;
}

Print Loop
Given a graph. We have to find the loop in the graph if it exist and
print the nodes of the loop in sorted order.

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

bool cycle(int a[MAX][MAX], bool *vis, bool *rec, int s, int n, int &cnt,
int *loop, int &cause, int &fla){
rec[s]=true;
vis[s]=true;

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


if(a[s][i]){
if(!vis[i]){
if(cycle(a,vis,rec,i,n,cnt,loop,cause,fla)){
if(fla==0)
loop[cnt++]=i;
if(i==cause)
fla=1;
return true;
}
}
else if(rec[i]){
cause=i;
return true;
}
}
}
rec[s]=false;
return false;
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int a[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin >> a[i][j];

bool vis[n], rec[n];


for(int i=0; i<n; i++){
vis[i]=false;
rec[i]=false;
}

int loop[n];

int flag=0, cnt=0, cause=-1, fla=0;


for(int i=0; i<n; i++){
if(!vis[i]){
if(cycle(a,vis,rec,i,n,cnt,loop,cause,fla)){
if(fla==0)
loop[cnt++]=i;
if(i==cause)
fla=1;
flag=1;
break;
}
}
}

if(flag==1){
sort(loop,loop+cnt);
for(int i=0; i<cnt; i++)
cout << loop[i] << " ";
cout << endl;
}
if(flag==0)
cout << "-1" << endl;
}
}

Wormholes and Spaceship


#include<iostream>
using namespace std;

struct point{
int x;
int y;
};

int main(){
int t;
cin >> t;

while(t--){
int sx, sy, dx, dy;
cin >> sx >> sy >> dx >> dy;

int n;
cin >> n;

int a[2*n+2][2*n+2];
for(int i=0; i<2*n+2; i++)
for(int j=0; j<2*n+2; j++)
a[i][j]=10000000;

struct point points[2*n];


for(int i=0; i<2*n; i=i+2){
int x1, x2, y1, y2, cost;
cin >> x1 >> y1 >> x2 >> y2 >> cost;

points[i].x=x1;
points[i].y=y1;
points[i+1].x=x2;
points[i+1].y=y2;

a[i][i+1]=cost;
a[i+1][i]=cost;
}

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


a[2*n][i]=abs(points[i].x-sx)+abs(points[i].y-sy);
a[i][2*n+1]=abs(points[i].x-dx)+abs(points[i].y-dy);
}
a[2*n][2*n]=0;
a[2*n+1][2*n+1]=0;
a[2*n][2*n+1]=abs(sx-dx)+abs(dx-dy);

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


for(int j=0; j<2*n; j++){
if(a[i][j]==10000000)
a[i][j]=abs(points[i].x-points[j].x)+abs(points[i].y-
points[j].y);
}
}

n=2*n+2;

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


for(int j=0; j<n; j++){
if(a[i][j]==10000000)
cout << "INF\t";
else
cout << a[i][j] << "\t";
}cout << endl;
}*/

//Floyd Warshall
int dist[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
dist[i][j]=a[i][j];

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


for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(dist[i][j]>dist[i][k]+dist[k][j])
dist[i][j]=dist[i][k]+dist[k][j];
}
}
}

cout << dist[n-2][n-1] << endl;


}
return 0;
}

N-Pots, Crow and Stones


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

struct bruh{
int big;
int com;
};

int main(){
int t;
cin >> t;

while(t--){
int n, k;
cin >> n >> k;

int a[n];
for(int i=0; i<n; i++)
cin >> a[i];

sort(a,a+n);

struct bruh info[n];


info[n-1].big=0;
info[n-1].com=0;
int prev=a[n-1];

for(int i=n-2; i>=0; i--){


if(a[i]==prev){
info[i].big=info[i+1].big;
info[i].com=info[i+1].com+1;
}else{
info[i].big=info[i+1].big+info[i+1].com+1;
info[i].com=0;
prev=a[i];
}
}

int sum[n];
sum[n-1]=a[n-1];
for(int i=n-2; i>=0; i--){
sum[i]=sum[i+1]+a[i];
}

int min=10000000;
for(int i=n-1; i>=k-1; i--){
int x=(info[i].big+info[i].com+1);
int stones=x*a[i];
if(i-(k-info[i].com-1)>=0)
stones+=sum[i-(k-info[i].com-1)]-sum[i];
if(stones<min)
min=stones;
}
cout << min << endl;
}
}

For Input:
1
12 5
1 2 2 3 3 3 3 3 5 9 9 11
Your Output is:
37
38
38
32
27
27
27
27
27

Balloon Burst Problem


class Solution {
public:
int maxCoins(vector<int>& nums) {
int n=nums.size();
if(n==0)
return 0;

int a[n+2];
a[0]=1;
a[n+1]=1;
for(int i=1; i<n+1; i++)
a[i]=nums[i-1];

int dp[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
dp[i][j]=0;

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


for(int i=0; i<=n-len; i++){
int j=i+len-1;
if(i==j){
dp[i][j]=a[i]*a[i+1]*a[i+2];
continue;
}
int ans=0;
for(int k=i; k<=j; k++){
int add=0;
if(k-1>=i)
add+=dp[i][k-1];
if(k+1<=j)
add+=dp[k+1][j];
ans=max(ans,add+a[i]*a[k+1]*a[j+2]);
}
dp[i][j]=ans;
}
}

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];
}
};

Maze and Jewels


#include<iostream>
using namespace std;
#define MAX 15

bool isvalid(int x, int y, int n){


return (x>=0 && x<n && y>=0 && y<n);
}

void dfs(int a[MAX][MAX], bool vis[MAX][MAX], int sx, int sy, int n, int
cnt, int &max){
if(sx==n-1 && sy==n-1){
if(cnt>max)
max=cnt;
return;
}

int row[]={0,0,1,-1};
int col[]={1,-1,0,0};
for(int i=0; i<4; i++){
int u=sx+row[i];
int v=sy+col[i];
if(isvalid(u,v,n) && !vis[u][v] && a[u][v]!=1){
vis[u][v]=true;
if(a[u][v]==2)
dfs(a,vis,u,v,n,cnt+1,max);
else
dfs(a,vis,u,v,n,cnt,max);
vis[u][v]=false;
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int a[MAX][MAX];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
cin >> a[i][j];
}

bool vis[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
vis[i][j]=false;

int max=0;
dfs(a,vis,0,0,n,0,max);

cout << max << endl;


}
}
Find element position in given monotonic sequence
#include<bits/stdc++.h>
using namespace std;
#define SMALL 1000000
#define LARGE 1000000000000000

long long int func(long long int a, long long int b, long long int c, long
long int n){
long long int A=a*n;
long long int logValue=floor(log2(n));
long long int B=b*n*logValue;
long long int C=c*n*n*n;
return A+B+C;
}

long long int position(long long int a, long long int b, long long int c,
long long int k){
long long int start=0, end=SMALL;
if(c==0)
end=LARGE;

long long int ans=0;


while(start<=end){
long long int mid=start+(end-start)/2;
long long int val=func(a,b,c,mid);
if(val==k){
ans=mid;
break;
}else if(val>k)
end=mid-1;
else if(val<k)
start=mid+1;
}
return ans;
}

int main(){
int t;
cin >> t;

while(t--){
long long int a, b, c;
cin >> a >> b>> c;

long long int k;


cin >> k;
cout << position(a,b,c,k) << endl;
}
}

Alien Dictionary
void topo(int a[MAX][MAX], stack<int> &st, bool *vis, int s){
vis[s]=true;

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


if(a[s][i] && !vis[i])
topo(a,st,vis,i);
}
st.push(s);
}

string printOrder(string dict[], int n, int k){


int a[MAX][MAX];
for(int i=0; i<26; i++)
for(int j=0; j<26; j++)
a[i][j]=0;

bool vis[26];
for(int i=0; i<26; i++)
vis[i]=true;

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


string word1=dict[i];
string word2=dict[i+1];

for(int j=0; j<min(word1.length(),word2.length()); j++){


if(word1[j]!=word2[j]){
vis[word1[j]-'a']=false;
vis[word2[j]-'a']=false;
a[word1[j]-'a'][word2[j]-'a']=1;
break;
}
}
}

stack<int> s;
for(int i=0; i<26; i++){
if(!vis[i])
topo(a,s,vis,i);
}

string str="";
while(!s.empty()){
str=str+(char)(s.top()+'a');
s.pop();
}

return str;
}

Recursively remove all the adjacent duplicates of string


#include<bits/stdc++.h>
using namespace std;
string rem(string s){
stack<char> st;
char prev=s[0];
st.push(s[0]);
int flag=0;
for(int i=1; i<s.length(); i++){
if(s[i]!=prev){
if(flag==1 && !s.empty())
st.pop();
st.push(s[i]);
prev=s[i];
flag=0;
}else
flag=1;
}
if(flag==1)
st.pop();

string str="";
while(!st.empty()){
str=st.top()+str;
st.pop();
}

return str;
}

int main(){
int t;
cin >> t;

while(t--){
string s;
cin >> s;

if(s.length()<2){
cout << s << endl;
continue;
}

while(1){
int n=s.length();
s=rem(s);
if(n==s.length())
break;
}

cout << s << endl;


}
return 0;
}

Old Mobile Trackpad


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

struct node{
string str;
int len;
bool op;
struct node *next;
};

void push(struct node **head, struct node **en, string str, int len, bool
op){
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->str=str;
temp->len=len;
temp->op=op;
temp->next=NULL;
if(*head==NULL){
*head=temp;
*en=temp;
}else{
(*en)->next=temp;
*en=temp;
}
}

void pop(struct node **head){


struct node *temp=*head;
*head=(*head)->next;
free(temp);
}

bool isvalid(string str){


int n=str.length()-1;
if(str[n]=='+' || str[n]=='-' || str[n]=='*' || str[n]=='/')
return false;
return true;
}

int evaluate(string s){


int n=s.length()-1;
int num1=0, num2=0, flag=0;
char operand;
for(int i=0; i<=n; i++){
if((s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/')){
if(flag==1){
if(operand=='+')
num1=num1+num2;
else if(operand=='-')
num1=num1-num2;
else if(operand=='*')
num1=num1*num2;
else if(operand=='/' && num2!=0)
num1=num1/num2;

num2=0;
flag=1;
}
operand=s[i];
flag=1;
}else{
if(flag==0)
num1=num1*10+(s[i]-'0');
else if(flag==1)
num2=num2*10+(s[i]-'0');
}
}

if(flag==1){
if(operand=='+')
num1=num1+num2;
else if(operand=='-')
num1=num1-num2;
else if(operand=='*')
num1=num1*num2;
else if(operand=='/' && num2!=0)
num1=num1/num2;
}

return num1;
}

void bfs(string s, int num, int o, int N, bool &flag){


struct node *q=NULL;
struct node *en=NULL;

string f="";
for(int i=0; i<N; i++)
push(&q,&en,f+s[i],1,false);

while(q){
string str=q->str;
int len=q->len;
bool op=q->op;
pop(&q);

if(isvalid(str) && evaluate(str)==num){


if(op)
flag=true;
mini=len;
return;
}

if(len==o)
continue;

int n=str.length()-1;
for(int i=0; i<s.length(); i++){
if(str[n]=='+' || str[n]=='-' || str[n]=='*' || str[n]=='/'){
if(!(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/'))
push(&q,&en,str+s[i],len+1,op);
}else{
if(s[i]=='+' || s[i]=='-' || s[i]=='*' ||
s[i]=='/')
push(&q,&en,str+s[i],len+1,true);
else
push(&q,&en,str+s[i],len+1,op);
}
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n, m, o;
cin >> n >> m >> o;

string s="";
for(int i=0; i<n; i++){
char ch;
cin >> ch;
s=s+ch;
}

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


char ch;
cin >> ch;
if(ch=='1')
s=s+'+';
else if(ch=='2')
s=s+'-';
else if(ch=='3')
s=s+'*';
else
s=s+'/';
}

int num;
cin >> num;

if(n==9){
int dig=0;
for(int i=num; i>0; i=num/10)
dig++;

if(dig>o)
cout << "-1" << endl;
else
cout << dig << endl;

continue;
}

bool flag=false;
mini=-1;
bfs(s,num,o,n,flag);

if(flag)
mini++;

cout << mini << endl;


}
}

Ford Flukerson
#include<bits/stdc++.h>
using namespace std;
#define MAX 1005

bool bfs(int res[MAX][MAX], int source, int sink, int *parent, int n){
bool vis[n];
for(int i=0; i<n; i++)
vis[i]=false;

queue<int> q;
q.push(source);
vis[source]=true;
parent[source]=-1;
while(!q.empty()){
int u=q.front();
q.pop();

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


if(!vis[v] && res[u][v]>0){
q.push(v);
parent[v]=u;
vis[v]=true;
}
}
}

return (vis[sink]==true);
}

int ford(int a[MAX][MAX], int source, int sink, int n){


int res[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
res[i][j]=a[i][j];

int parent[n];
int maxflow=0;

while(bfs(res,source,sink,parent,n)){
int pathflow=INT_MAX;
int u, v;
for(v=sink; v!=source; v=parent[v]){
u=parent[v];
pathflow=min(pathflow,res[u][v]);
}

for(v=sink; v!=source; v=parent[v]){


u=parent[v];
res[u][v]-=pathflow;
res[v][u]+=pathflow;
}

maxflow+=pathflow;
}

return maxflow;
}

int main(){
int t;
cin >> t;

while(t--){
int n, m;
cin >> n >> m;

int a[MAX][MAX];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
a[i][j]=0;

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


int u, v, w;
cin >> u >> v >> w;
a[u-1][v-1]+=w;
a[v-1][u-1]+=w;
}

cout << ford(a,0,n-1,n) << endl;


}
return 0;
}

Robot Car Fueling


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

void bruh(vector<int> &car, int gas, int des, int fuel, int pos, int n, int
dist, int &mdist){
if(gas==0 && des==0){
if(dist<mdist)
mdist=dist;
return;
}

if(pos==-1 || pos==n){
if(pos==-1){
if(fuel==2 || gas==0)
return;
fuel=-2;
bruh(car,gas,des,fuel,pos+1,n,dist+1,mdist);
}else if(pos==n){
if(fuel==-2 || des==0)
return;
fuel=2;
bruh(car,gas,des,fuel,pos-1,n,dist+1,mdist);
}
}else{
if(fuel>0){
bruh(car,gas,des,fuel,pos-1,n,dist+1,mdist);
if(car[pos]==2){
car[pos]=0;
bruh(car,gas,des-1,0,n,n,dist+n-pos,mdist);
bruh(car,gas,des-1,fuel-1,pos-1,n,dist+1,mdist);
car[pos]=2;
}
}else if(fuel<0){
bruh(car,gas,des,fuel,pos+1,n,dist+1,mdist);
if(car[pos]==1){
car[pos]=0;
bruh(car,gas-1,des,0,-1,n,dist+pos+1,mdist);
bruh(car,gas-1,des,fuel+1,pos+1,n,dist+1,mdist);
car[pos]=1;
}
}else if(fuel==0){
if(gas)
bruh(car,gas,des,0,-1,n,dist+pos+1,mdist);
if(des)
bruh(car,gas,des,0,n,n,dist+n-pos,mdist);
}
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

vector<int> car;
int gas=0, des=0;
for(int i=0; i<n; i++){
int a;
cin >> a;
car.push_back(a);

if(a==1)
gas++;
else
des++;
}

int mdist=INT_MAX;
bruh(car,gas,des,0,-1,n,0,mdist);

cout << mdist-1 << endl;


}
return 0;
}

Construction Basestation
#include<bits/stdc++.h>
using namespace std;
#define X 20

bool safe(int x, int y, int n, int m){


return (x>=0 && x<n && y>=0 && y<m);
}

void bruh(int a[X][X], bool vis[X][X], int u, int v, int sum, int depth,
int n, int m, int &max, vector<pair<int,pair<int,int>>> vec){

if(v%2==0){
int row[]={-1,-1,-1,0,0,0,1};
int col[]={-1,0,1,-1,0,1,0};
for(int i=0; i<7; i++){
int x=u+row[i];
int y=v+col[i];

if(safe(x,y,n,m) && !vis[x][y])


vec.push_back(make_pair(a[x][y],make_pair(x,y)));
}
}else{
int row[]={-1,0,0,0,1,1,1};
int col[]={0,-1,0,1,-1,0,1};
for(int i=0; i<7; i++){
int x=u+row[i];
int y=v+col[i];

if(safe(x,y,n,m) && !vis[x][y])


vec.push_back(make_pair(a[x][y],make_pair(x,y)));
}
}

if(depth==3){
sort(vec.begin(),vec.end());
for(int i=vec.size()-1; i>=0; i--){
if(!vis[vec[i].second.first][vec[i].second.second]){
sum+=vec[i].first;
break;
}
}

if(sum>max)
max=sum;
return;
}

if(v%2==0){
int row[]={-1,-1,-1,0,0,0,1};
int col[]={-1,0,1,-1,0,1,0};

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


int x=u+row[i];
int y=v+col[i];

if(safe(x,y,n,m) && !vis[x][y]){


vis[x][y]=true;
bruh(a,vis,x,y,sum+a[x][y],depth+1,n,m,max,vec);
vis[x][y]=false;
}
}
}else{
int row[]={-1,0,0,0,1,1,1};
int col[]={0,-1,0,1,-1,0,1};

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


int x=u+row[i];
int y=v+col[i];

if(safe(x,y,n,m) && !vis[x][y]){


vis[x][y]=true;
bruh(a,vis,x,y,sum+a[x][y],depth+1,n,m,max,vec);
vis[x][y]=false;
}
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n, m;
cin >> n >> m ;

int a[X][X];
bool vis[X][X];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin >> a[i][j];
vis[i][j]=false;
}
}

int max=0, extra=0;


vector<pair<int,pair<int,int>>> v;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
vis[i][j]=true;
bruh(a,vis,i,j,a[i][j],1,n,m,max,v);
vis[i][j]=false;
}
}

cout << max << endl;


}
return 0;
}

TollGate
#include<iostream>
using namespace std;

void bruh(int *men, int *cost, int pos, int b3, int b2, int b1, int n, int
sum, int &t_cost){
if(sum>=t_cost)
return;

if(pos==n){
if(sum<t_cost)
t_cost=sum;
return;
}

bruh(men,cost,pos+1,b3,b2,b1,n,sum+cost[pos],t_cost);
bruh(men,cost,pos+1,b3+men[pos],b2,b1,n,sum+2*cost[pos],t_cost);

int pep=b3+b2+b1;
if(pep>=men[pos]){
if(men[pos]>b2+b1){
b3=pep-men[pos];
b2=0;
b1=0;
}else if(men[pos]>b1){
b2=b2+b1-men[pos];
b1=0;
}
bruh(men,cost,pos+1,0,b3,b2,n,sum,t_cost);
}
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

int men[n], cost[n];


for(int i=0; i<n; i++){
cin >> men[i] >> cost[i];
}

int t_cost=1000000;
bruh(men,cost,0,0,0,0,n,0,t_cost);

cout << t_cost << endl;


}
return 0;
}

New research centre for Rare Elements


#include<iostream>
using namespace std;
#define X 21

struct node{
int x;
int y;
int dist;
struct node *next;
};

bool safe(int x, int y, int n){


return (x>=0 && x<n && y>=0 && y<n);
}

void push(struct node **head, struct node **end, int x, int y, int dist){
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->x=x;
temp->y=y;
temp->dist=dist;
temp->next=NULL;
if(*head==NULL){
*head=temp;
*end=*head;
}else{
(*end)->next=temp;
*end=temp;
}

void bfs(int a[X][X], int vis[X][X], int dist[X][X], int x_cord, int
y_cord, int d, int re, int n){
struct node *head=NULL;
struct node *end=head;

push(&head,&end,x_cord,y_cord,d);
while(head){
struct node *temp=head;
head=head->next;

int u=temp->x;
int v=temp->y;
int dis=temp->dist;

int row[]={1,0,-1,0};
int col[]={0,-1,0,1};

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


int x=u+row[i];
int y=v+col[i];

if(safe(x,y,n) && a[x][y]==1 && vis[x][y]!=re){


vis[x][y]++;
push(&head,&end,x,y,dis+1);
dist[x][y]=max(dist[x][y],dis+1);
}
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n, rare;
cin >> n >> rare;

int elements[rare][2];
for(int i=0; i<rare; i++){
int x, y;
cin >> x >> y;

elements[i][0]=x-1;
elements[i][1]=y-1;
}

int a[X][X];
int vis[X][X];
int dist[X][X];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> a[i][j];
vis[i][j]=0;
dist[i][j]=0;
}
}

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


bfs(a,vis,dist,elements[i][0],elements[i][1],0,i+1,n);
}

int ans=100000;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(vis[i][j]==rare){
if(dist[i][j]<ans)
ans=dist[i][j];
}
}
}

cout << ans << endl;


}
return 0;
}

Bipartite
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 cases when a graph is not
connected.

bool dfs(int g[][MAX], int color[], int v, int u){


for(int i=0; i<v; i++){
if(g[u][i]==1 && color[i]==-1){
color[i]=1-color[u];
if(!dfs(g,color,v,i))
return false;
}else if(g[u][i]==1 && color[i]==color[u])
return false;
}

return true;
}

bool isBipartite(int G[][MAX],int V){


int color[V];
for(int i=0; i<V; i++)
color[i]=-1;

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


if(color[i]==-1){
color[i]=0;
if(!dfs(G,color,V,i))
return false;
}
}

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


if(color[i]==0)
cout << i << " ";
}cout << endl;
return true;
}

Finding Day of a Week for a Given Date


int main(){
int t;
cin >> t;

while(t--){
int d, m, y;
cin >> d >> m >> y;
int year=y;
y--;
y=y%400;

//int a[]={5,3,1,0};
int odd=0;
if(y>=100 && y<200)
odd=5;
else if(y>=200 && y<300)
odd=3;
else if(y>=300)
odd=1;
y=y%100;
odd+=(y/4)*2 + (y-(y/4));

int month[]={3,0,3,2,3,2,3,3,2,3,2,3};
if(year%400==0 || ((year%100)!=0 && (year%4)==0))
month[1]=1;

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


odd+=month[i];
odd+=d;

odd=odd%7;
string day[]={"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
cout << day[odd] << endl;
}
return 0;
}

Mr Lee Travels
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.

#include<iostream>
using namespace std;
#define X 20

void bruh(int mat[X][X], bool vis[], int s, int v, int n, int c, int
&cost){
if(v==n){
if(c+mat[s][0]<cost)
cost=c+mat[s][0];
return;
}

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


if(mat[s][i]!=0 && !vis[i]){
vis[i]=true;
bruh(mat,vis,i,v+1,n,c+mat[s][i],cost);
vis[i]=false;
}
}
}

int main(){
int t;
cin >> t;

while(t--){
int n;
cin >> n;

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

bool vis[n];
for(int i=0; i<n; i++)
vis[i]=false;

int cost=1000000;
bruh(mat,vis,0,1,n,0,cost);
cout << cost << endl;
}

return 0;
}

Toggling

#include<iostream>
using namespace std;

int main(){
int t;
cin >> t;

while(t--){
int n, m, k;
cin >> n >> m >> k;

int a[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++)
cin >> a[i][j];
}
int dp[1048576]={0};
for(int i=0; i<n; i++){
int num=0;
for(int j=m-1; j>=0; j--){
num=num*2;
if(a[i][j]==1)
num=num+1;
}
dp[num]++;
}

int max=-1;
for(int i=0; i<1048576; i++){
if(dp[i]>0 && dp[i]>max){
int unset=0;
int temp=i;
while(temp>0){
int a=temp&1;
if(a==0)
unset++;
temp>>=1;
}
if(unset<=k && (k-unset)%2==0)
max=dp[i];
}
}

cout << max << endl;


}
return 0;
}

You might also like