Find the maximum value permutation of a graph - GeeksforGeeks

07 Jun, 2021
Given a graph containing N nodes. For any permutation of nodes P1, P2, P3, ..., PN the value of the permutation is defined as the number of indices which have at least 1 node on the left of it that has an edge to it. Find the maximum value across all permutations.Examples:  
Input: N = 3, edges[] = {{1, 2}, {2, 3}} Output: 2 Consider the permutation 2 1 3 Node 1 has node 2 on the left of it and there is an edge connecting them in the graph. Node 3 has node 2 on the left of it and there is an edge connecting them in the graph.Input: N = 4, edges[] = {{1, 3}, {2, 4}} Output: 2 Consider the permutation 1 2 3 4 Node 3 has node 1 on the left of it and there is an edge connecting them in the graph. Node 4 has node 2 on the left of it and there is an edge connecting them in the graph.  
 
Approach: Let’s start with any node at the beginning, we can follow it up with any node adjacent to it and repeat the process. This resembles a dfs traversal in which every node except the first node has a node before it with which it shares an edge. So for every connected component, the maximum value we can get for the permutation of the nodes of this component is Size of component – 1.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of nodes// in the current connected componentint dfs(int x, vector<int> adj[], int vis[]){    // Initialise size to 1    int sz = 1;     // Mark the node as visited    vis[x] = 1;     // Start a dfs for every unvisited    // adjacent node    for (auto ch : adj[x])        if (!vis[ch])            sz += dfs(ch, adj, vis);     // Return the number of nodes in    // the current connected component    return sz;} // Function to return the maximum value// of the required permutationint maxValue(int n, vector<int> adj[]){    int val = 0;    int vis[n + 1] = { 0 };     // For each connected component    // add the corresponding value    for (int i = 1; i <= n; i++)        if (!vis[i])            val += dfs(i, adj, vis) - 1;    return val;} // Driver codeint main(){    int n = 3;    vector<int> adj[n + 1] = { { 1, 2 }, { 2, 3 } };    cout << maxValue(n, adj);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static int vis[]; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, Vector<Vector<Integer>> adj){    // Initialise size to 1    int sz = 1;     // Mark the node as visited    vis[x] = 1;     // Start a dfs for every unvisited    // adjacent node    for (int i = 0; i < adj.get(x).size(); i++)        if (vis[adj.get(x).get(i)] == 0)            sz += dfs(adj.get(x).get(i), adj);     // Return the number of nodes in    // the current connected component    return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, Vector<Vector<Integer>> adj){    int val = 0;    vis = new int[n + 1];         for (int i = 0; i < n; i++)    vis[i] = 0;     // For each connected component    // add the corresponding value    for (int i = 0; i < n; i++)        if (vis[i] == 0)            val += dfs(i, adj) - 1;    return val;} // Driver codepublic static void main(String args[]){    int n = 3;    Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>() ;         // create the graph    Vector<Integer> v = new Vector<Integer>();    v.add(0);    v.add(1);    Vector<Integer> v1 = new Vector<Integer>();    v1.add(1);    v1.add(2);         adj.add(v);    adj.add(v1);    adj.add(new Vector<Integer>());         System.out.println( maxValue(n, adj));}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # Function to return the number of nodes# in the current connected componentdef dfs(x, adj, vis):     # Initialise size to 1    sz = 1     # Mark the node as visited    vis[x] = 1     # Start a dfs for every unvisited    # adjacent node    for ch in adj:        if (not vis[ch]):            sz += dfs(ch, adj, vis)     # Return the number of nodes in    # the current connected component    return sz # Function to return the maximum value# of the required permutationdef maxValue(n, adj):     val = 0    vis = [0] * (n + 1)     # For each connected component    # add the corresponding value    for i in range(1, n + 1):        if (not vis[i]):            val += dfs(i, adj, vis) - 1    return val # Driver Codeif __name__ == '__main__':    n = 3    adj = [1, 2 , 2, 3]    print(maxValue(n, adj)) # This code is contributed by# SHUBHAMSINGH10
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int []vis ; // Function to return the number of nodes// in the current connected componentstatic int dfs(int x, List<List<int>> adj){    // Initialise size to 1    int sz = 1;     // Mark the node as visited    vis[x] = 1;     // Start a dfs for every unvisited    // adjacent node    for (int i = 0; i < adj[x].Count; i++)        if (vis[adj[x][i]] == 0)            sz += dfs(adj[x][i], adj);     // Return the number of nodes in    // the current connected component    return sz;} // Function to return the maximum value// of the required permutationstatic int maxValue(int n, List<List<int>> adj){    int val = 0;    vis = new int[n + 1];         for (int i = 0; i < n; i++)        vis[i] = 0;     // For each connected component    // add the corresponding value    for (int i = 0; i < n; i++)        if (vis[i] == 0)            val += dfs(i, adj) - 1;    return val;} // Driver codepublic static void Main(String []args){    int n = 3;    List<List<int>> adj = new List<List<int>>() ;         // create the graph    List<int> v = new List<int>();    v.Add(0);    v.Add(1);    List<int> v1 = new List<int>();    v1.Add(1);    v1.Add(2);         adj.Add(v);    adj.Add(v1);    adj.Add(new List<int>());         Console.WriteLine( maxValue(n, adj));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Function to return the number of nodes// in the current connected componentfunction dfs(x, adj, vis){    if(x>1)        return 1;             // Initialise size to 1    var sz = 1;     // Mark the node as visited    vis[x] = 1;    // Start a dfs for every unvisited    // adjacent node    adj[x].forEach(ch => {                 if (!vis[ch])            sz += dfs(ch, adj, vis);    });     // Return the number of nodes in    // the current connected component    return sz;} // Function to return the maximum value// of the required permutationfunction maxValue(n, adj){    var val = 0;    var vis = Array(n+1).fill(0);     // For each connected component    // add the corresponding value    for (var i = 0; i < n; i++)        if (!vis[i])            val += dfs(i, adj, vis) - 1;    return val;} // Driver codevar n = 2;var adj =  [ [ 0, 1 ], [ 1, 2] ];document.write( maxValue(n, adj)); // This code is contributed by famously.</script>
2
 
Time Complexity: O(N) 
andrew1234
SHUBHAMSINGH10
Rajput-Ji
famously
DFS
Algorithms
Graph
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Difference between Informed and Uninformed Search in AI
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5