- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a tree, and the weights of all the nodes and an integer x. We have to find the node i, such that |weight[i] - x| is minimum. If the graph is like below, and x = 15

Output will be 3. Now for different nodes, it will be like below

Node 1, |5 – 15| = 10

Node 2, |10 – 15| = 5

Node 3, |11 – 15| = 4

Node 4, |8 – 15| = 7

Node 5, |6 – 15| = 9

The idea is simple. We will perform the DFS on the tree, and keep track of the node, whose weighted absolute difference with x gives the minimum value

#include <iostream> #include <vector> #include <cmath> using namespace std; int min_value = INT_MAX, x, result; vector<int> graph[100]; vector<int> weight(100); void dfs(int node, int parent) { if (min_value > abs(weight[node] - x)) { min_value = abs(weight[node] - x); result = node; } for (int to : graph[node]) { if (to == parent) continue; dfs(to, node); } } int main() { x = 15; weight[1] = 5; weight[2] = 10; weight[3] = 11; weight[4] = 8; weight[5] = 6; graph[1].push_back(2); graph[2].push_back(3); graph[2].push_back(4); graph[1].push_back(5); dfs(1, 1); cout << "The node number is: " << result; }

The node number is: 3

- Related Questions & Answers
- Maximum absolute difference of value and index sums in C
- Find a value whose XOR with given number is maximum in C++
- Maximum of Absolute Value Expression in C++
- Count maximum elements of an array whose absolute difference does not exceed K in C++
- Find maximum value of x such that n! % (k^x) = 0 in C++
- Absolute difference between the first X and last X Digits of N?
- Program to find maximum adjacent absolute value sum after single reversal in C++
- Maximum Difference Between Node and Ancestor in C++
- Maximum sum of absolute difference of any permutation in C++
- Count numbers whose sum with x is equal to XOR with x in C++
- Find the node with minimum value in a Binary Search Tree in C++
- Count smaller values whose XOR with x is greater than x in C++
- Find the first natural number whose factorial is divisible by x in C++
- Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++
- Find Nth positive number whose digital root is X in C++

Advertisements