3 849
Suscriptores
Sin datos24 horas
-297 días
-12730 días
Archivo de publicaciones
3 849
#include <iostream>
using namespace std;
void merge(int arr[], int left[], int left_size, int right[], int right_size) {
int i = 0, j = 0, k = 0;
while (i < left_size && j < right_size) {
if (left[i] < right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < left_size) {
arr[k++] = left[i++];
}
while (j < right_size) {
arr[k++] = right[j++];
}
}
void mergeSortOdd(int arr[], int n) {
if (n <= 1) {
return;
}
int mid = n / 2;
int left[mid];
int right[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = arr[i];
}
mergeSortOdd(left, mid);
mergeSortOdd(right, n - mid);
merge(arr, left, mid, right, n - mid);
}
//awasthi
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int oddCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
oddCount++;
}
}
if (oddCount == 0) {
cout << "None" << endl;
} else {
mergeSortOdd(arr, n);
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
cout << arr[i] << " ";
}
}
cout << endl;
}
return 0;
}
3 849
Sarah is an avid programmer who loves to solve interesting problems. Today, she encountered a unique challenge related to sorting odd numbers from an array of integers. She wants to sort the odd numbers in ascending order while keeping the even numbers in their original positions.
Sarah has contacted you for help with this challenge. Can you implement both the logic of merge sort and a recursive function to achieve the above task?
Input format :
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, representing the elements of the array.
3 849
#include <stdio.h>
int countMoves(int n, char source, char auxiliary, char destination) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return 1;
}
//awasthi
int moves1 = countMoves(n - 1, source, destination, auxiliary);
printf("Move disk %d from %c to %c\n", n, source, destination);
int moves2 = countMoves(n - 1, auxiliary, source, destination);
return moves1 + 1 + moves2;
}
int main() {
int n;
scanf("%d", &n);
char source = 'A';
char auxiliary = 'B';
char destination = 'C';
int totalMoves = countMoves(n, source, auxiliary, destination);
printf("Total number of moves: %d\n", totalMoves);
return 0;
}
3 849
You are tasked with organizing a set of numbered disks (1 to n) on three pegs labeled A, B, and C. The disks are initially stacked in ascending order of size on peg A. Your goal is to move all the disks from peg A to peg C using the Towers of Hanoi game rules.
Each move involves transferring one disk at a time, and you must follow the rules:
Only one disk can be moved at a time.
Each move consists of taking the top disk from one of the pegs and placing it on top of another peg.
A larger disk cannot be placed on top of a smaller disk.
You need to write a recursive function, countMoves(n), that takes the number of disks n as input and returns the total number of moves required to solve the Towers of Hanoi problem.
For example, if the number of disks is 3, the disks can be transferred as follows: The total number of moves made is 7.
3 849
#include <iostream>
using namespace std;
long long power(long long a, long long b) {
if (b == 0) {
return 1;
} else if (b % 2 == 0) {
long long half_pow = power(a, b / 2);
return (half_pow * half_pow);
} else {
long long half_pow = power(a, (b - 1) / 2);
return (a * half_pow * half_pow);
}
}
//awasthi
int main() {
int T;
cin >> T;
while (T--) {
long long a, b;
cin >> a >> b;
long long result = power(a, b);
cout << result << endl;
}
return 0;
}
3 849
You are given T test cases, each consisting of two integers, 'a' and 'b'. Your task is to calculate 'a' raised to the power of 'b' and output the result for each test case.
You need to implement the exponentMod() function that efficiently calculates the modular exponentiation of 'a' raised to the power of 'b', using recursion and modular arithmetic.
Note: This kind of question will be helpful in clearing Infosys recruitment.
Input format :
The first line of input consists of an integer T, representing the number of test cases.
Each of the following T lines contains two space-separated integers a and b, where a is the base, and b is the exponent.
Output format :
For each test case, the output prints a single integer on a new line, representing the result of 'a' raised to the power of 'b'.
3 849
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, arr [i], representing the values of the nodes in the binary tree. The elements are given in the order of a binary tree, where the i-th element is the value of the i-th node.
Output format :
The output displays a single line containing n space-separated integers, which represent the postorder traversal of the binary tree constructed from the input array.
3 849
Vinith is working on a programming assignment that involves binary search trees (BSTs). He needs to implement a program that constructs a BST from a given list of integers and then calculates two important pieces of information: the post-order traversal of the tree and the sum of all nodes within the tree.
Input format :
The first line of input contains an integer n, representing the number of integers Vinith will provide to construct the BST.
The second line contains n space-separated integers, data, representing the values to be inserted into the BST.
Output format :
The first line should display the post-order traversal of the binary search tree.
The second line should display the sum of all nodes in the binary search tree.
3 849
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class BST {
private:
TreeNode* root;
int sum;
public:
BST() : root(nullptr), sum(0) {}
void insertNode(int val) {
root = insert(root, val);
}
TreeNode* insert(TreeNode* root, int val) {
if (root == nullptr) {
return new TreeNode(val);
}
if (val <= root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
void postOrderTraversal() {
std::cout << "Post-order traversal: ";
postOrderTraversal(root);
std::cout << std::endl;
}
void postOrderTraversal(TreeNode* root) {
if (root == nullptr)
return;
postOrderTraversal(root->left);
postOrderTraversal(root->right);
std::cout << root->val << " ";
}
void calculateSum() {
sum = calculateSum(root);
std::cout << "\nSum of all nodes: " << sum << std::endl;
}
//awasthi
int calculateSum(TreeNode* root) {
if (root == nullptr)
return 0;
int leftSum = calculateSum(root->left);
int rightSum = calculateSum(root->right);
return root->val + leftSum + rightSum;
}
};
int main() {
int n;
std::cin >> n;
BST bst;
int val;
for (int i = 0; i < n; ++i) {
std::cin >> val;
bst.insertNode(val);
}
bst.postOrderTraversal();
bst.calculateSum();
return 0;
}
3 849
#include <iostream>
#include <vector>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class BinaryTree {
private:
TreeNode* root;
std::vector<int> postorderTraversal;
public:
BinaryTree() : root(nullptr) {}
void buildTree(const std::vector<int>& arr) {
root = buildTree(arr, 0);
}
TreeNode* buildTree(const std::vector<int>& arr, int index) {
if (index >= arr.size())
return nullptr;
TreeNode* node = new TreeNode(arr[index]);
node->left = buildTree(arr, 2 * index + 1);
node->right = buildTree(arr, 2 * index + 2);
return node;
}
void initiatePostorderTraversal() {
postorderTraversalRecursive(root);
}
void postorderTraversalRecursive(TreeNode* root) {
if (root == nullptr)
return;
postorderTraversalRecursive(root->left);
postorderTraversalRecursive(root->right);
postorderTraversal.push_back(root->val);
}
std::vector<int> getPostorderTraversal() const {
return postorderTraversal;
}
};
//awasthi
int main() {
int n;
std::cin >> n;
std::vector<int> arr(n);
for (int i = 0; i < n; ++i)
std::cin >> arr[i];
BinaryTree tree;
tree.buildTree(arr);
tree.initiatePostorderTraversal();
std::vector<int> postorder = tree.getPostorderTraversal();
//std::cout << "Post-order traversal: ";
for (int i = 0; i < postorder.size(); ++i) {
std::cout << postorder[i];
if (i < postorder.size() - 1)
std::cout << " ";
}
std::cout << std::endl;
return 0;
}
3 849
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class TaskScheduler {
private:
TreeNode* root;
public:
TaskScheduler() : root(nullptr) {}
void insertTask(int taskID) {
root = insert(root, taskID);
}
TreeNode* insert(TreeNode* root, int taskID) {
if (root == nullptr) {
return new TreeNode(taskID);
}
if (taskID < root->val) {
root->left = insert(root->left, taskID);
} else {
root->right = insert(root->right, taskID);
}
return root;
}
void postOrderTraversal() {
std::cout << "Post order Traversal:" << std::endl;
postOrderTraversal(root);
std::cout << std::endl;
}
void postOrderTraversal(TreeNode* root) {
if (root == nullptr)
return;
postOrderTraversal(root->left);
postOrderTraversal(root->right);
std::cout << root->val << " ";
}
};
//awasthi
int main() {
TaskScheduler taskScheduler;
int taskID;
while (true) {
std::cin >> taskID;
if (taskID == -1)
break;
taskScheduler.insertTask(taskID);
}
taskScheduler.postOrderTraversal();
return 0;
}
3 849
Madhu is responsible for developing a program to manage a task scheduler. Each task is identified by a unique task ID, which is a positive integer.
Your task is to implement a program that reads task IDs as input until a sentinel value (-1) is entered, constructs a binary search tree with the task IDs, and then performs post-order traversal to display the tasks in the scheduler.
Input format :
The input consists of a series of positive integers representing the product IDs of items added to the shopping cart. The input ends when a negative integer (-1) is entered.
Output format :
The post-order traversal of the binary search tree displays the product IDs of items in the shopping cart.
3 849
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
Node* insert(Node* root, int data) {
if (root == nullptr) {
return new Node(data);
} else {
Node* cur = new Node(data);
if (root->left == nullptr) {
root->left = cur;
} else if (root->right == nullptr) {
root->right = cur;
} else {
// If both left and right children are already present,
// you can choose one side to insert the new node, e.g., left.
root->left = insert(root->left, data);
}
return root;
}
}
void postOrder(Node* root) {
if (root != nullptr) {
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}
}
int main() {
Node* root = nullptr;
int n;
int data;
cin >> n;
while (n-- > 0) {
cin >> data;
root = insert(root, data);
}
//awasthi
postOrder(root);
return 0;
}
3 849
Venugopal is studying data structures and wants to build a program that can create a binary tree from a list of integers and then perform a postorder traversal on the constructed tree.
Create a Binary Tree: Venugopal can provide a list of integers to create a binary tree.
Perform Postorder Traversal: Venugopal can perform a postorder traversal on the constructed binary tree.
Input format :
The first line contains an integer n, denoting the number of integers in the list.
The second line contains 'n' space-separated integers representing the elements of the list.
Output format :
The output displays a single line containing space-separated integers representing the postorder traversal of the binary tree.
3 849
#include <iostream>
#include <vector>
// Node structure for the binary tree
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Helper function to construct the binary tree from given values
TreeNode* constructBinaryTree(std::vector<int>& values, int& index, int n) {
if (index >= n || values[index] == -1) {
index++;
return nullptr;
}
TreeNode* root = new TreeNode(values[index++]);
root->left = constructBinaryTree(values, index, n);
root->right = constructBinaryTree(values, index, n);
return root;
}
// Preorder traversal to calculate the sum of values in the binary tree
int preorderTraversal(TreeNode* root) {
if (root == nullptr)
return 0;
int sum = root->val;
sum += preorderTraversal(root->left);
sum += preorderTraversal(root->right);
return sum;
}
int main() {
int N;
std::cin >> N;
std::vector<int> values(N);
for (int i = 0; i < N; ++i) {
std::cin >> values[i];
}
int index = 0;
TreeNode* root = constructBinaryTree(values, index, N);
int totalValue = preorderTraversal(root);
std::cout << totalValue << std::endl;
// TODO: Free allocated memory for tree nodes (not shown in this example for simplicity)
//awasthi
return 0;
}
3 849
You are working on a financial application that deals with investment portfolios represented as a binary tree. Each node in the binary tree represents a specific investment and holds a numerical value indicating the investment's worth.
Your task is to implement an algorithm in your financial application, which will allow you to accurately calculate the total value of the investment portfolio represented by the binary tree, facilitating better decision-making and analysis for your clients.
The algorithm performs a preorder traversal of the binary tree, where the value of the current node is added to the sum before visiting its children. By visiting each node in a prearranged manner, we ensure that every element in the tree is accounted for in the sum calculation.
Input format :
The first line of input consists of a single integer N, representing the number of nodes in the binary tree.
The second line consists of N space-separated integers, representing the values of the nodes in the binary tree.
3 849
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : val(value), left(nullptr), right(nullptr) {}
};
TreeNode* insert(TreeNode* root, int bookID) {
if (root == nullptr)
return new TreeNode(bookID);
if (bookID < root->val)
root->left = insert(root->left, bookID);
else if (bookID > root->val)
root->right = insert(root->right, bookID);
return root;
}
void inOrderTraversal(TreeNode* root) {
if (root == nullptr)
return;
inOrderTraversal(root->left);
std::cout << root->val << " ";
inOrderTraversal(root->right);
}
int main() {
int N;
std::cin >> N;
TreeNode* root = nullptr;
for (int i = 0; i < N; ++i) {
int bookID;
std::cin >> bookID;
root = insert(root, bookID);
}
//std::cout << "Output: ";
inOrderTraversal(root);
std::cout << "\n";
//awasthi
// Free allocated memory
// You can implement a function to delete the tree nodes and call it here
return 0;
}
3 849
Amla is the librarian at a local library. She needs a tool to manage the library's catalog efficiently.
She decides to use a program that can organize the book IDs in ascending order to help her locate books more easily.
Write a program that allows Sarah to input the book IDs one by one. The program should then construct a binary search tree with the book IDs and display the book IDs in ascending order using an in-order traversal.
Input format :
The first line of input consists of an integer N, the number of books in the library.
The next line consists of N positive integers separated by space, representing the unique book IDs.
3 849
#include <iostream>
#include <vector>
// Structure for a binary tree node
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Function to create a new node with a given value
TreeNode* createNode(int value) {
return new TreeNode(value);
}
// Function to perform preorder traversal and convert the tree to its mirror image
void convertToMirror(TreeNode* root) {
if (root == nullptr)
return;
// Swap left and right subtrees
std::swap(root->left, root->right);
// Recur for left subtree
convertToMirror(root->left);
// Recur for right subtree
convertToMirror(root->right);
}
// Function to perform preorder traversal of the binary tree
void preorderTraversal(TreeNode* root, std::vector<int>& result) {
if (root == nullptr)
return;
// Visit the current node
result.push_back(root->val);
// Traverse left subtree
preorderTraversal(root->left, result);
// Traverse right subtree
preorderTraversal(root->right, result);
}
int main() {
int n;
std::cin >> n;
TreeNode* root = nullptr;
// Input the values and create the binary tree
for (int i = 0; i < n; ++i) {
int value;
std::cin >> value;
if (i == 0) {
root = createNode(value);
} else {
TreeNode* node = root;
while (true) {
if (value < node->val) {
if (node->left == nullptr) {
node->left = createNode(value);
break;
}
node = node->left;
} else {
if (node->right == nullptr) {
node->right = createNode(value);
break;
}
node = node->right;
}
}
}
}
std::vector<int> originalPreorder;
std::vector<int> mirrorPreorder;
// Perform preorder traversal of the original tree
std::cout << "Original tree: ";
preorderTraversal(root, originalPreorder);
for (int val : originalPreorder) {
std::cout << val << " ";
}
std::cout << std::endl;
// Convert the tree to its mirror image
convertToMirror(root);
//awasthi
// Perform preorder traversal of the mirror image tree
std::cout << "Mirror Image: ";
preorderTraversal(root, mirrorPreorder);
for (int val : mirrorPreorder) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
3 849
Rahul is working on a program for a tree manipulation application. Your task is to help Rahul implement a program that converts a given binary tree into its mirror image using preorder traversal.
Your program should traverse the binary tree in a preordered manner and swap the left and right subtrees of each node to achieve the mirror image.
Write a function that performs the conversion to the mirror image using a preorder traversal approach. The function should take the root of the binary tree as input and modify the tree to obtain its mirror image.
Input format :
The first line of input consists of an integer N, representing the number of nodes in the binary tree.
The second line consists of N space-separated integers representing the values of the nodes.
Output format :
The first line of output should display the preorder traversal of the original binary tree.
The second line should display the preorder traversal of the binary tree after converting it into its mirror image.
