Kruskal (MST): Really Special Subtree

Sort by

recency

|

189 Discussions

|

  • + 0 comments

    What is wrong with mys solution - ? public static int kruskals(int gNodes, List gFrom, List gTo, List gWeight) { var edges = new List>(); for (int i = 0; i < gFrom.Count; i++) { edges.Add(new Tuple(gFrom[i], gTo[i], gWeight[i])); }

    edges = edges
        .OrderBy(e => e.Item3)
        .ThenBy(e => e.Item1)
        .ToList();
    
    var visitedNodes = new HashSet<int>();
    var mstEdges = new List<Tuple<int, int, int>>();
    for (int i = 0; i < edges.Count; i++)
    {
        if (!visitedNodes.Contains(edges[i].Item2))
        {
            mstEdges.Add(edges[i]);
            visitedNodes.Add(edges[i].Item2);
        }
        if (mstEdges.Count == gNodes - 1)
            break;
    }
    
    var totalWeight = mstEdges.Sum(e => e.Item3);
    return totalWeight;
    

    }

  • + 0 comments

    VoIP technology is continuously evolving, with ongoing advancements in features, capabilities, and integration options. Providers are constantly innovating to incorporate emerging technologies such as Artificial Intelligence (AI), machine learning, and advanced analytics into their VoIP systems. This commitment to innovation ensures that VoIP services remain at the forefront of communication technology VoIP Phone Services, offering businesses and individuals access to the latest tools and solutions to stay competitive and adapt to future developments.

  • + 0 comments

    C++ (more at https://github.com/IhorVodko/Hackerrank_solutions/tree/master , feel free to give a star:) )

    bool areNodesInTheSameTree(
        vector<bool> const & nodesVisited,
        std::unordered_map<int, vector<int>> const & nodeToNeighbours,
        int const nodeA,
        int const nodeB,
        int const nodesCount
    ){
        using namespace std;
        if(!(nodesVisited.at(nodeA) && nodesVisited.at(nodeB))){
            return false;
        }
        auto nodesVisitedBfs{vector<bool>(nodesCount + 1, false)};
        auto qBfs{queue<int>{}};
        qBfs.push(nodeA);
        nodesVisitedBfs.at(nodeA) = true;
        auto nodeCurrent{qBfs.front()};
        while(!qBfs.empty()){
            nodeCurrent = qBfs.front();
            qBfs.pop();
            for(auto const nodeNext: nodeToNeighbours.at(nodeCurrent)){
                if(nodeNext == nodeB){
                    return true;
                }
                if(nodesVisitedBfs.at(nodeNext)){
                    continue;
                }
                qBfs.push(nodeNext);
                nodesVisitedBfs.at(nodeNext) = true;
            }
        }
        return false;
    }
    
    int kruskals(
        int const nodesCount,
        std::vector<int> const & nodesFrom,
        std::vector<int> const & nodesTo,
        std::vector<int> const & edgeWeightes
    ){
        using namespace  std;
        auto weightToEdges{multimap<int, pair<int, int>>{}};
        for(size_t idx{0}; idx != edgeWeightes.size(); ++idx){
            weightToEdges.insert({edgeWeightes.at(idx), {nodesFrom.at(idx),
                nodesTo.at(idx)}});
        }
        cout << weightToEdges.size() << '\n';
        auto nodeToNeighbours{unordered_map<int, vector<int>>{}};
        auto weightSubtree{0};
        auto nodesVisited{vector<bool>(nodesCount + 1, false)};
        for(auto const & [weight, edge]: weightToEdges){
            if(::areNodesInTheSameTree(nodesVisited, nodeToNeighbours, edge.first,
                edge.second, nodesCount)
            ){
                continue;
            }
            nodeToNeighbours[edge.first].emplace_back(edge.second);
            nodeToNeighbours[edge.second].emplace_back(edge.first);
            nodesVisited.at(edge.first) = true;
            nodesVisited.at(edge.second) = true;
            weightSubtree += weight;
        }
        return weightSubtree;
    }
    
  • + 0 comments

    My python solution

    def kruskals(g_nodes, g_from, g_to, g_weight):
        edges = sorted(zip(g_from, g_to, g_weight), key=lambda x: x[2])
        mst = {}
        cost = 0
        for c, (u, v, w) in enumerate(edges):
            d = {}
            for idx, conn in mst.items():
                if (u in conn):
                    d[u] = idx
                if (v in conn):
                    d[v] = idx
            if d.get(u, -1) != d.get(v, -2):
                cost += w
        return cost
                mst[c] = mst.pop(d.get(u, -1), set([u])) | mst.pop(d.get(v, -1), set([v]))
            
        return cost
    
    `
    
  • + 0 comments

    include

    using namespace std;

    string ltrim(const string &); string rtrim(const string &); vector split(const string &);

    /* * Complete the 'kruskals' function below. * * The function is expected to return an INTEGER. * The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. */

    int findParent(vector& parent, int x) { if (parent[x] == x) return x; return parent[x] = findParent(parent, parent[x]); }

    void unionSet(vector& parent, vector& rank, int x, int y) { int rootX = findParent(parent, x); int rootY = findParent(parent, y); if (rootX != rootY) { if (rank[rootX] < rank[rootY]) { parent[rootX] = rootY; } else if (rank[rootX] > rank[rootY]) { parent[rootY] = rootX; } else { parent[rootY] = rootX; rank[rootX]++; } } }

    int kruskals(int g_nodes, vector g_from, vector g_to, vector g_weight) { int numEdges = g_from.size(); vector>> edges(numEdges); for (int i = 0; i < numEdges; ++i) { edges[i] = {g_weight[i], {g_from[i], g_to[i]}}; } sort(edges.begin(), edges.end());

    vector<int> parent(g_nodes + 1);
    vector<int> rank(g_nodes + 1, 0);
    for (int i = 0; i <= g_nodes; ++i) {
        parent[i] = i;
    }
    
    int minWeight = 0;
    for (auto& edge : edges) {
        int w = edge.first;
        int u = edge.second.first;
        int v = edge.second.second;
        if (findParent(parent, u) != findParent(parent, v)) {
            unionSet(parent, rank, u, v);
            minWeight += w;
        }
    }
    return minWeight;
    

    }

    int main() { ofstream fout(getenv("OUTPUT_PATH"));

    string g_nodes_edges_temp;
    getline(cin, g_nodes_edges_temp);
    
    vector<string> g_nodes_edges = split(rtrim(g_nodes_edges_temp));
    
    int g_nodes = stoi(g_nodes_edges[0]);
    int g_edges = stoi(g_nodes_edges[1]);
    
    vector<int> g_from(g_edges);
    vector<int> g_to(g_edges);
    vector<int> g_weight(g_edges);
    
    for (int i = 0; i < g_edges; i++) {
        string g_from_to_weight_temp;
        getline(cin, g_from_to_weight_temp);
    
        vector<string> g_from_to_weight = split(rtrim(g_from_to_weight_temp));
    
        int g_from_temp = stoi(g_from_to_weight[0]);
        int g_to_temp = stoi(g_from_to_weight[1]);
        int g_weight_temp = stoi(g_from_to_weight[2]);
    
        g_from[i] = g_from_temp;
        g_to[i] = g_to_temp;
        g_weight[i] = g_weight_temp;
    }
    
    int result = kruskals(g_nodes, g_from, g_to, g_weight);
    
    fout << result << "\n";
    
    fout.close();
    
    return 0;
    

    }

    string ltrim(const string &str) { string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );
    
    return s;
    

    }

    string rtrim(const string &str) { string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );
    
    return s;
    

    }

    vector split(const string &str) { vector tokens;

    string::size_type start = 0;
    string::size_type end = 0;
    
    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));
    
        start = end + 1;
    }
    
    tokens.push_back(str.substr(start));
    
    return tokens;
    

    }