Cod sursa(job #2808432)

Utilizator jaha01Jahaleanu Vlad-Gabriel jaha01 Data 25 noiembrie 2021 01:56:28
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.48 kb
#include <iostream>
#include <bits/stdc++.h>

#define MAX_SIZE 10000

using namespace std;

ifstream fapm("apm.in");
ofstream gapm("apm.out");


class Graf
{
    int nrNoduri;
    int nrMuchii;

    vector<vector<pair<int,int>>> costs;



public:

    void citire_apm();

    void APM();
    int nodCostMin(vector<int> &helper, vector<bool> &includeInMst);



};


void Graf::citire_apm()
{
    costs.resize(nrNoduri + 1);
    int nod1, nod2, cost;
    pair<int,int> temp;

    fapm>>nrNoduri>>nrMuchii;

    for(int i = 0; i < nrMuchii; i++)
    {
        fapm>>nod1>>nod2>>cost;

        temp.first = nod2;
        temp.second = cost;

        costs[nod1].push_back(temp);
        temp.first = nod1;
        costs[nod2].push_back(temp);
    }

}



int Graf::nodCostMin(vector<int> &helper, vector<bool> &includeInMst)
{
    int minimum, indexOfMin;
    minimum  = INT_MAX;

    for(int i = 1; i <= nrNoduri; i++)
        if(includeInMst[i] == false && helper[i] < minimum)
        {
            minimum = helper[i];
            indexOfMin = i;
        }

    return indexOfMin;
}
void Graf::APM()
{
    vector<int> parent;            //un fel de vector de tati
    vector<bool> includeInMst;        //un fel de visited
    vector<int> helper;         //cele mai mici costuri din nodul curent
                                //se updateaza la fiecare pas

    for(int i = 0 ; i <= nrNoduri; i++)
    {
        helper.push_back(INT_MAX);
        includeInMst.push_back(false);
        parent.push_back(0);
    }


    helper[1] = 0;
    parent[1] = -1;
    for(int i = 1 ; i <= nrNoduri; i++)
    {
        int nextVertex = nodCostMin(helper, includeInMst);  //gasim urmatorul nod cu muchia de cost minim
        includeInMst[nextVertex] = true;

        for(int j = 0; j < costs[nextVertex].size(); j++)
        {   int temp1 = costs[nextVertex][j].first;
            int temp2 = costs[nextVertex][j].second;

            if(includeInMst[temp1] == false && temp2 < helper[temp1])
            {
                parent[temp1] = nextVertex;
                helper[temp1] = temp2;
            }

        }

    }
    int sum = 0;
    for(int  i = 2; i <= nrNoduri; i++)
        sum += helper[i];



    cout<<sum<<"\n";
    cout<<nrNoduri - 1<<"\n";
    for(int  i = 2; i <= nrNoduri; i++)
        cout<<parent[i]<<" "<<i<<"\n";

}


int main()
{
    Graf G;

    G.citire_apm();

    G.APM();

    return 0;
}