
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the node whose absolute difference with X gives maximum value in C++
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
Example
#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; }
Output
The node number is: 3
- Related Articles
- Maximum absolute difference of value and index sums in C
- Find a value whose XOR with given number is maximum in C++
- Count maximum elements of an array whose absolute difference does not exceed K in C++
- Maximum of Absolute Value Expression in C++
- Write the number whose absolute value is $\frac{5}{6}$.
- 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++
- Absolute difference between the first X and last X Digits of N?
- Python program to find the maximum and minimum value node from a circular linked list
- Python program to find the maximum and minimum value node from a doubly linked list
- Find the node with minimum value in a Binary Search Tree in C++
- Maximum absolute difference of the length of strings from two arrays in JavaScript
- Find maximum value of x such that n! % (k^x) = 0 in C++
- Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++

Advertisements