You are viewing a single comment's thread. Return to all comments →
I followed everything suggested still getting wrong answer in test cases #2, #3, #5, #7, #8, #9 and #13 here is my code
import java.io.*; import java.util.*; class Graph{ long V; LinkedList<Long> adj[]; private boolean[] visited; private long result=0; Graph(long v){ V=v; adj=new LinkedList[(int)v]; visited=new boolean[(int)v]; for (int i=0; i<(int)v; ++i) adj[i] = new LinkedList(); } public void addEdge(long v, long w){ adj[(int)v].add(w); } public long dfsUtil(int v, long size){ visited[v]=true; Iterator<Long> i = adj[v].listIterator(); while(i.hasNext()){ long n=i.next(); size++; dfsUtil((int)n, size); } return size; } public void DFS(){ result=0; long siz=0; long sum=0; for(int i=0; i<V; i++){ if(visited[i]==false){ siz=dfsUtil(i, 1); result=result+sum*siz; sum=sum+siz; } } } public long getResult(){ return result; } } public class Solution { public static void main(String[] args) throws Exception{ BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in)); String[] temp = bfr.readLine().split(" "); long N = Long.parseLong(temp[0]); long I = Long.parseLong(temp[1]); Graph g = new Graph(N); for(int i = 0; i < I; i++){ temp = bfr.readLine().split(" "); long a = Long.parseLong(temp[0]); long b = Long.parseLong(temp[1]); g.addEdge(a, b); } g.DFS(); long combinations = g.getResult(); System.out.println(combinations); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
I followed everything suggested still getting wrong answer in test cases #2, #3, #5, #7, #8, #9 and #13 here is my code