
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 the Maximum Value Permutation of a Graph in C++
In this problem, we are given a graph of N nodes. Our task is to Find the maximum possible value of the minimum value of the modified array.
For the graph we have a permutation of nodes which is the number of induces with minimum 1 node on the left of it sharing a common edge.
Let’s take an example to understand the problem,
Input : N = 4, edge = {{1, 2}, {2, 3}, {3, 4}, {4, 1}} Output : 3
Solution Approach
A simple solution to the problem is by traversing the tree from one node visiting all its adjacent nodes. We will find the permutation of nodes using the formula of the number of nodes connected to it.
The formula is,
Size of component - 1.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; int dfs(int x, vector<int> adjMat[], int visited[]){ int sz = 1; visited[x] = 1; for (auto ch : adjMat[x]) if (!visited[ch]) sz += dfs(ch, adjMat, visited); return sz; } int maxValPermutationGraph(int n, vector<int> adjMat[]){ int val = 0; int visited[n + 1] = { 0 }; for (int i = 1; i <= n; i++) if (!visited[i]) val += dfs(i, adjMat, visited) - 1; return val; } int main(){ int n = 4; vector<int> adjMat[n + 1] = {{1, 2}, {2, 3}, {3, 4}, {4, 1}}; cout<<"The maximum value permutation of a graph is "<<maxValPermutationGraph(n, adjMat); return 0; }
Output
The maximum value permutation of a graph is 3
Advertisements