# Sum of dependencies in a graph

Given a directed and connected graph with n nodes. If there is an edge from u to v then u depends on v. Our task was to find out the sum of dependencies for every node.

Example:
For the graph in diagram,
A depends on C and D i.e. 2
B depends on D i.e. 1
C depends on D i.e. 1
And D depends on none.
Hence answer -> 0 + 1 + 1 + 2 = 4

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Idea is to check adjacency list and find how many edges are there from each vertex and return the total number of edges.

## C++

// C++ program to find the sum of dependencies
#include <bits/stdc++.h>
using namespace std;

{
}

// find the sum of all dependencies
{
int sum = 0;

// just find the size at each vector's index
for (int u = 0; u < V; u++)

return sum;
}

// Driver code
int main()
{
int V = 4;

cout << "Sum of dependencies is "
return 0;
}

## Java

// Java program to find the sum of dependencies

import java.util.Vector;

class Test
{
{
}

// find the sum of all dependencies
static int findSum(Vector<Integer> adj[], int V)
{
int sum = 0;

// just find the size at each vector's index
for (int u = 0; u < V; u++)

return sum;
}

// Driver method
public static void main(String[] args)
{
int V = 4;

for (int i = 0; i < adj.length; i++) {
}

System.out.println("Sum of dependencies is " +
}
}
// This code is contributed by Gaurav Miglani

Output:

Sum of dependencies is 4

Time complexity : O(V) where V is number of vertices in graph.

This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.2 Average Difficulty : 1.2/5.0
Based on 20 vote(s)