สมมติว่าเรามีต้นไม้ และน้ำหนักของโหนดทั้งหมดและจำนวนเต็ม x เราต้องหาโหนด i เช่นนั้น |weight[i] - x| เป็นขั้นต่ำ หากกราฟเป็นดังนี้ และ x =15

เอาต์พุตจะเป็น 3 สำหรับโหนดต่างๆ จะเป็นดังนี้
โหนด 1, |5 – 15| =10
โหนด 2, |10 – 15| =5
โหนด 3, |11 – 15| =4
โหนด 4, |8 – 15| =7
โหนด 5, |6 – 15| =9
ความคิดนั้นง่าย เราจะดำเนินการ DFS บนแผนผัง และติดตามโหนด ซึ่งความแตกต่างแบบสัมบูรณ์แบบถ่วงน้ำหนักกับ x จะให้ค่าต่ำสุด
ตัวอย่าง
#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