Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
C++ Program to find out the super vertices in a graph
Suppose, we are given a graph that has n vertices. The vertices are numbered 1 to n, and they are connected by the edges given in the array 'edges'. Each vertex has an 'x' value within a number from 1 to n that is given in the array 'values'. Now, we have to find out the super vertices from the graph. A vertex i is called a 'super vertex' whenever the shortest path from vertex 1 to i doesn't have a vertex with the same 'x' value as the i-th vertex. We print out all the vertices satisfying this criterion.

So, if the input is like n = 5, values = {1, 2, 2, 1, 3}, edges = {{1, 2}, {2, 3}, {2, 3}, {2, 4}, {4, 5}}, then the output will be 1 3 4 5.
Every vertex except vertex 2 satisfies the criterion. So, vertex 2 is excluded.
Steps
To solve this, we will follow these steps −
Define arrays vertexVal, frq, and chk of size: 100005. Define an array vcti of size 200005. Define a function dfs(), this will take j, k, if frq[vertexVal[j]] is same as 0, then: chk[j] := 1 (increase frq[vertexVal[j]] by 1) for each value a in vcti[j], do: if a is not equal to k, then: dfs(a, j) (decrease frq[vertexVal[j]] by 1) for initialize i := 0, when iExample
Let us see the following implementation to get better understanding −
#includeusing namespace std; int n; int vertexVal[100005], frq[100005], chk[100005]; vector vcti[200005]; void dfs(int j, int k){ if (frq[vertexVal[j]] == 0) chk[j] = 1; frq[vertexVal[j]]++; for (auto a : vcti[j]) { if (a != k) dfs(a, j); } frq[vertexVal[j]]--; } void solve(int values[], vector > edges){ for (int i = 0; i > edges = {{1, 2}, {2, 3}, {2, 3}, {2, 4}, {4, 5}}; solve(values, edges); return 0; } Input
5, {1, 2, 2, 1, 3}, {{1, 2}, {2, 3}, {2, 3}, {2, 4}, {4, 5}}Output
1 3 4 5
