Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find triplet such that number of nodes connecting these triplets is maximum in C++
In this tutorial, we will be discussing a program to find triplet such that number of nodes connecting these triplets is maximum.
For this we will be provided with a tree with N nodes. Our task is to find a triplet of nodes such that the nodes covered in the path joining them in maximum.
Example
#include <bits/stdc++.h>
#define ll long long int
#define MAX 100005
using namespace std;
vector<int> nearNode[MAX];
bool isTraversed[MAX];
//storing the required nodes
int maxi = -1, N;
int parent[MAX];
bool vis[MAX];
int startnode, endnode, midNode;
//implementing DFS to search nodes
void performDFS(int u, int count) {
isTraversed[u] = true;
int temp = 0;
for (int i = 0; i < nearNode[u].size(); i++) {
if (!isTraversed[nearNode[u][i]]) {
temp++;
performDFS(nearNode[u][i], count + 1);
}
}
if (temp == 0) {
if (maxi < count) {
maxi = count;
startnode = u;
}
}
}
void performDFS2(int u, int count) {
isTraversed[u] = true;
int temp = 0;
for (int i = 0; i < nearNode[u].size(); i++) {
if (!isTraversed[nearNode[u][i]] && !vis[nearNode[u][i]]) {
temp++;
performDFS2(nearNode[u][i], count + 1);
}
}
if (temp == 0) {
if (maxi < count) {
maxi = count;
midNode = u;
}
}
}
//finding endnote of diameter
void performDFS1(int u, int count) {
isTraversed[u] = true;
int temp = 0;
for (int i = 0; i < nearNode[u].size(); i++) {
if (!isTraversed[nearNode[u][i]]) {
temp++;
parent[nearNode[u][i]] = u;
performDFS1(nearNode[u][i], count + 1);
}
}
if (temp == 0) {
if (maxi < count) {
maxi = count;
endnode = u;
}
}
}
void calcTreeVertices() {
performDFS(1, 0);
for (int i = 0; i <= N; i++)
isTraversed[i] = false;
maxi = -1;
performDFS1(startnode, 0);
for (int i = 0; i <= N; i++)
isTraversed[i] = false;
int x = endnode;
vis[startnode] = true;
while (x != startnode) {
vis[x] = true;
x = parent[x];
}
maxi = -1;
for (int i = 1; i <= N; i++) {
if (vis[i])
performDFS2(i, 0);
}
}
int main() {
N = 4;
nearNode[1].push_back(6);
nearNode[2].push_back(0);
nearNode[1].push_back(7);
nearNode[3].push_back(0);
nearNode[1].push_back(2);
nearNode[4].push_back(0);
calcTreeVertices();
cout << "Nodes: (" << startnode << ", " << endnode << ", " << midNode << ")";
return 0;
}
Output
Nodes: (0, 0, 0)
Advertisements