Question

Algorithm/Implementation in Java please. Josefine has spent the entire summer deciding what courses she wants to...

Algorithm/Implementation in Java please.

Josefine has spent the entire summer deciding what courses she wants to study at The University of Algorithms. A course takes one semester to finish (and as the super student she is, she always succeeds). Some of the courses depends on other courses, and it is therefore not allowed to take these in the same semester. If course i depends on course j, Josefine must take course i in an earlier semester than course j. She wants to finish her studies in as few semesters as possible.

Given the N courses Josefine wants to study (numbered from 1 to N), and the courses they each depend on, compute the fewest number of semesters Josefine needs to use to finish her studies. (Again, she is a super student, so she can take an unlimited number of courses each semester).

You can assume there is no cyclic dependencies in the courses Josefine has chosen.

Input format

  • Line 1: The integers N and M (1 <= N <= 1.000.000) where N is the number of courses and M is the total number of dependencies.
  • Line 2..M+1: Two integers X and Y meaning the course X depends on the course Y (ie. course Y must have been completed before course X)

Output format

  • Line 1: The fewest number of semesters Josefine needs to use.

Restrictions

You are free to use all built-in modules/packages/functions in Java. You are not allowed to use any other modules/packages/code/etc from the internet or similar.

Sample input/output data:

Input (stdin)

5 4
1 3
2 3
4 1
4 2

Expected Output

3
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Algorithm used here is topological sort

dfs is used top implemet topological sort .in normal dfs we push a vertex in stack then call dfs for its adjacent vertices but in this first we call dfs for its adjacent then push it in stack.and instead of using boolean visited array use integer visited array and initialise it to -1.and visited[v] will be 1+max(visited[adjacent[v]) this implies that after doing vth subject atleast max(visited[adjacent(v)] semesters will be required

In the end return max(visited of all vertices)

import java.util.*;
import java.lang.*;
import java.io.*;
class graph
{
   //number of vertices
   private int V;
   //adjacency list
   private LinkedList adj[];
   //constructor
   graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i adj[i] = new LinkedList();
}
//add edge function
void addEdge(int v,int w) { adj[v].add(w); }
void topologicalSortUtil(int v, int visited[], Stack stack)
{
Integer i;
//iterator of adjacency list of v
Iterator it = adj[v].iterator();
//x stores max value of visited of vertices adjacent to v
int x=-1;
//loop through each adjacent vertex of v
while (it.hasNext())
{
i = it.next();
//if it is not visited
if (visited[i]!=-1)
topologicalSortUtil(i, visited, stack);
//x=max(x,visited[i])
if(x x=visited[i];
  
}
//set visited[v]=1+x
//if a course is to be done at last sem its visited will be 0
//that's why while returning answer 1 is added
visited[v]=1+x;
//push v in stack
stack.push(new Integer(v));
}
int topologicalSort()
{
Stack stack = new Stack();
int visited[] = new int[V];
//initialise visited to -1
for (int i = 0; i < V; i++)
visited[i]=-1;
//call helper function for all verices which are not -1
for (int i = 0; i < V; i++)
if (visited[i] == -1)
topologicalSortUtil(i, visited, stack);
//ans stores number of semester required
int ans=-1;
for(int i=0;i {
   if(ans    ans=visited[i];
}
//as visisted is initialised with -1 so return 1+ans
return ans+1;
}
   public static void main (String[] args) throws java.lang.Exception
   {
       //take input
       Scanner sc=new Scanner(System.in);
       int n,e;
       n=sc.nextInt();
       e=sc.nextInt();
       graph g=new graph(n);
       for(int i=0;i        {
           int x,y;
           x=sc.nextInt();
           y=sc.nextInt();
           g.addEdge(x,y);
       }
       int ans=g.topologicalSort();
       System.out.println(ans);
   }
}

Ideone.com-Online Compiler and IDE>> C/C++, Java, PHP, Python, Perl and 40+ other compilers and interpreters-Google Chrome 1.

Add a comment
Know the answer?
Add Answer to:
Algorithm/Implementation in Java please. Josefine has spent the entire summer deciding what courses she wants to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Program 5 Due 10/25 C-String and Two-dimensional Array Use An input data file starts with a...

    Program 5 Due 10/25 C-String and Two-dimensional Array Use An input data file starts with a student's name (on one line). Then, for each course the student took last semester, the file has 2 data lines. The course name is on the first line. The second line has the student's grade average (0 to 100) and the number of credits for the course Sample data: Jon P. Washington, Jr. Computer Science I 81 4 PreCalculus 75 3 Biology I 88...

  • Please code in java There are N employees already working for a company and M new...

    Please code in java There are N employees already working for a company and M new candidates eligible for the work. At the end of the financial year, each of the N employees demand for an increment. You are provided with the data of current_salary and the salary he/she expects. Also, there are M candidates we can recruit. We have the data of salary demanded by each eligible candidate. The company can spend maximum of X units of money. Now...

  • A company wants to invest into building a golf course. They could choose the land to...

    A company wants to invest into building a golf course. They could choose the land to build the course from a rectangle area of size MxN. The rectangle area is divided into MxN cells. They measured the elevation of each cell and recorded it into an integer number. The company decided that the golf course should be a KxK square (K ≤ min(M,N)). Thus, there are (M-K+1)(NK+1) possible KxK squares that can be used to build the golf course. For...

  • Java code ABOVE AVERAGE 40 Input Standard input Output Standard output Topic Array & Array Processing...

    Java code ABOVE AVERAGE 40 Input Standard input Output Standard output Topic Array & Array Processing Problem Description Understanding how to interpret test scores is a valuable skill for every teacher. That's because test score interpretation enables teachers to understand how their students' performance for each tests of the course. Average test score is one of the indicators to determine the class performance for the test. For each test, we need to calculate the average score and determine the percentage...

  • Please write a Java program that ask the user how many beers he or she expects...

    Please write a Java program that ask the user how many beers he or she expects to consume each day, on average, as well as the average amount of money he or she spends on a single 12-ounce can of beer. Studies have shown that, on average, someone who consumes a single 12-ounce can of beer every day without compensating for the calorie intake through diet modifications or extra exercise, will gain approximately 15 pounds in one year. You can...

  • Debug and fix the Java console application that uses 2 dimensional arrays but the application does...

    Debug and fix the Java console application that uses 2 dimensional arrays but the application does not compile nor execute. Student enters only integers to select courses for registration from a menu. No data type validation of the user menu selection is checked or required. The program terminates only when the student closes it. No registration of other courses not displayed by the program . No registration more than once for the same course. No registration for more than 9...

  • a. You have 5 problems in this assignment. b. G++ compiler will be used to compile...

    a. You have 5 problems in this assignment. b. G++ compiler will be used to compile your source codes. c. Your program will be tested on Ubuntu 16.04. d. You are not allowed to use global variables in your implementation. e. Your program will get two arguments, input and output file names, from the command line: >> Your_Executable INPUT_FILE_NAME OUTPUT_FILE_NAME 1. Given a number ? , we initially have ?+1 different sets which are {0}, {1}, {2}, ... , {?}....

  • Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code...

    Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code that uses selection sort to place the elements of an integer array into non-decreasing order is shown here: public void swapNumbers(int i, int j) { ​int temp = numbers[i];​ /* put numbers[i] somewhere to keep it safe */ ​numbers[i] = numbers[j]; /* put numbers[j] at index i */ ​numbers[j] = temp;​ /* put numbers[i] at index j */ } public void selectionSort(int[] numbers) {...

  • Hello everyone. I have a bankers algorithm written in java that gets inputs from a .txt...

    Hello everyone. I have a bankers algorithm written in java that gets inputs from a .txt file. The file has 7 processes and 5 resources however, when the program runs, it doesn't sum the resource columns correctly. The program runs correctly for smaller matricies (4 processes, 3 resources), not sure what the issue is and have been looking over the code for awhile so maybe another set of eyes would help...thanks BankersAlgorithm.java /** * This program implements Bankers algorithm which...

  • use java There are n students in a class and n numbered chairs. The instructor has...

    use java There are n students in a class and n numbered chairs. The instructor has assigned a presentation for each student and is going to select the order of presentations by the following scheme. A number m is chosen. Beginning at seat number 1, she counts to m. The student sitting in that seat presents first. Then she starts counting seats again, starting from the next seat, wrapping around at the end, and skipping any student who has already...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT