Advertisement
Kostiggig

Untitled

Mar 31st, 2023
1,248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.67 KB | None | 0 0
  1. fun main() {
  2.  
  3.  
  4.     print(solve(
  5.         6,
  6.         listOf(
  7.             Pair(1, 2),
  8.             Pair(2, 1),
  9.             Pair(4, 1),
  10.             Pair(3, 4),
  11.             Pair(2, 5),
  12.             Pair(2, 4),
  13.             Pair(3, 5),
  14.             Pair(1, 5),
  15.             Pair(4, 5),
  16.             Pair(2,6),
  17.             Pair(6,5),
  18.         )
  19.     ))
  20. }
  21.  
  22. fun solve(cities: Int, adjacency: List<Pair<Int, Int>>) : Int{
  23.     val map: MutableMap<Int, MutableList<Int>> = mutableMapOf()
  24.     for (cityNumber in 1..cities) {
  25.         map[cityNumber] = mutableListOf()
  26.     }
  27.  
  28.  
  29.     for (cityNumber in 1..cities) {
  30.         adjacency.forEach { (from, where) ->
  31.             if (cityNumber == from) {
  32.                 val adjacencyOfCity = map[cityNumber] ?: mutableListOf()
  33.                 adjacencyOfCity.add(where)
  34.             }
  35.         }
  36.     }
  37.  
  38.     println(map)
  39.  
  40.     val numberOfEmptyRoadCities = mutableListOf<Int>()
  41.  
  42.     for (cityNumber in 1..cities) {
  43.         val where = map[cityNumber] ?: mutableListOf()
  44.         if (where.isEmpty()) numberOfEmptyRoadCities.add(cityNumber)
  45.     }
  46.  
  47.     println(numberOfEmptyRoadCities)
  48.  
  49.     val blackList = HashSet<Int>()
  50.     // O(k) * O(n) * O(m)
  51.     numberOfEmptyRoadCities.forEach { emptyRoadsCity ->
  52.         for (cityNumber in 1..cities) {
  53.             if (cityNumber == emptyRoadsCity) continue
  54.  
  55.             val where = map[cityNumber] ?: mutableListOf()
  56.             if (!where.contains(emptyRoadsCity)) {
  57.                 blackList.add(emptyRoadsCity)
  58.                 break
  59.             }
  60.         }
  61.     }
  62.  
  63.     for (number in numberOfEmptyRoadCities) {
  64.         if (!blackList.contains(number)) return number
  65.     }
  66.  
  67.     return -1
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement