• + 0 comments

    I spent quite some time to figure out why my solution didnt pass the 7 heavy input test cases. It turned out that since i tried to convert the edge list to adjacency matrix, the test ran out of memory. So instead of adjacency matrix, i use std::map as adjacency list. map> toAdjList(int n, vector> cities) { map> result = {}; for (const auto &ct : cities) { int a = ct[0]; int b = ct[1]; if (result.find(a) == result.end()) { result[a] = vector(); } result[a].push_back(b); if (result.find(b) == result.end()) { result[b] = vector(); } result[b].push_back(a); }

    return result;
    

    }

    long roadsAndLibraries(int n, int c_lib, int c_road, vector> cities) { if (n == 0) return 0; if (n == 1) return c_lib;

    vector<bool> visited(n + 1, 0);
    map<int, vector<int>> adjList = toAdjList(n, cities);
    
    long totalCost = 0;
    queue<int> q;
    std::cout << "processig " << n << std::endl;    
    for (int i = 1; i <= n; i++) {
        if (visited[i]) continue;
    
        q.push(i);
        visited[i] = true;
        long nodeCount = 1;
        while (!q.empty()) {
            int currNode = q.front();
            q.pop();
            for (const auto &adjNode : adjList[currNode]) {
                if (!visited[adjNode]) {
                    q.push(adjNode);
                    visited[adjNode] = true;
                    nodeCount++;
                }
            }
        }
        totalCost += std::min(nodeCount * c_lib, c_lib + (nodeCount - 1) * c_road);
    }
    
    return totalCost; 
    

    } `