Cod sursa(job #2266976)

Utilizator Andrei0872Gatej Andrei Andrei0872 Data 23 octombrie 2018 00:21:26
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb

#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

int V, *parent;

vector<pair<int,pair<int,int> > > adj; 
vector<pair<int,int> > result;

// Getting input
void test1() {
    int cost, n1, n2;
    ifstream f("apm.in");
    f >> V;
    parent = new int[V];
    while(!f.eof()) {
        f >> cost >> n1 >> n2;
        adj.push_back(make_pair(cost,make_pair(n1,n2)));
    }

    f.close();
}

int find(int node) {
    if(node != parent[node]) {
        parent[node] = find(parent[node]);
    }
    return parent[node];
}

void solve() {
    int first,second, currentCost, finalCost = 0;
    for(int i = 0; i < V; i++)
        parent[i] = i;

    sort(adj.begin(), adj.end());

    for(auto elem : adj) {
        currentCost = elem.first;
        first = elem.second.first;
        second = elem.second.second;

        // If the 2 nodes don't have the same parent
        if(find(first) != find(second)) {
            finalCost += currentCost;
            result.push_back({first,second});
            parent[parent[second]] = parent[first];
        }
    }

    ofstream g("apm.out");
    g << finalCost << "\n";
    g << result.size() << "\n";
    for(auto elem : result) {
        g << elem.first << " " << elem.second << "\n";
    }   

    g.close();
}

int main () {
    test1();
    solve();
    return 0;
}