Baegyang Road Break
InterviewTime limit1sMemory limit256 MB
Given a graph with one-way and two-way roads, answer many queries for the minimum number of one-way roads to reverse to reach each destination.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
Y University in Seoul started a large construction project, and the campus turned into a maze. Before the work began you could walk from any building to every other building. After it started, for reasons nobody can explain, the number of roads that go only one way grew a lot.
Namgyu, a computer science student, got lost on his way from a major class to an elective. After three days and nights of wandering he concluded that there is no route at all from the Engineering Hall to the Main Hall.
Three days of missed assignments and missed attendance put Namgyu one step from academic probation, so he decided to put his major to work. He would find out how many of the current one-way roads must be turned into two-way roads, then bring the result to the university.
Namgyu surveyed every road that directly connects two buildings and wrote down which ones are one-way and which ones are two-way.
His program is simple. You give it a start and a destination, and it reports the smallest number of roads that must be turned into two-way roads to get there. Word spread that the program was finished, and students who had been lost themselves started asking Namgyu questions.
"Can I get from the Engineering Hall to the Auditorium?"
"What about from the Business Annex to the Student Union?"
Namgyu wore himself out typing each question in by hand and sending the answer back, and he ended up sick in bed. Write the program that answers all of the students' questions for him at once.
Input
The first line has the number of buildings and the number of roads at Y University. (, )
Each of the next lines describes one road as . (, , , is 0 or 1)
If is 0, the road is one-way and can only be walked from to . If is 1, the road between and can be walked in both directions.
At most one road directly connects any two buildings.
The next line has the number of student questions . ()
Each of the next lines holds one question as . (, ) The student who asked wants to go from building to building .
Output
Print lines.
For each question, print on its own line the smallest number of one-way roads that must be turned into two-way roads so that you can walk from building to building . The roads you turn are counted separately for every question. Roads turned for an earlier question have no effect on a later one.
If every road is turned into a two-way road, no pair of buildings is unreachable from each other.