Roads and Libraries

  • + 0 comments

    solution in C#:

        public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<int>> cities)
        {
            if(n == 0) return 0;
            if(c_lib <= c_road) return n * (long)c_lib;
            
            var connections = new Dictionary<int, List<int>>();
            for(int c = 1; c <= n; c++)
            {
                connections[c] = new List<int>();
            }
            foreach(var cityPair in cities)
            {
                connections[cityPair[0]].Add(cityPair[1]);
                connections[cityPair[1]].Add(cityPair[0]);
            }
            
            var queue = new Queue<int>();
            var visited = new HashSet<int>();
            var cost = 0L;
            
            for(int c = 1; c <= n; c++)
            {
                if(visited.Contains(c))
                {
                    continue;
                }
                
                cost += c_lib;
                queue.Enqueue(c);
                visited.Add(c);
                while(queue.Count > 0)
                {
                    var city = queue.Dequeue();
                    foreach(var neighbour in connections[city])
                    {
                        if(!visited.Contains(neighbour))
                        {
                            queue.Enqueue(neighbour);
                            visited.Add(neighbour);
                            cost += c_road;
                        }
                    }
                }
            }
            return cost;
        }