Cod sursa(job #3201805)

Utilizator stefan2806Radulescu Stefan stefan2806 Data 9 februarie 2024 19:27:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
#include <queue>
#define max_value 2000

using namespace std;

ifstream cin("apm.in");
ofstream cout("apm.out");

int n,m,i,x,y,c,t[200010];
long long d[200010];
bool viz[200010];

struct NodeCost
{
    int nod;
    int cost;

    bool operator <(const NodeCost a)const
    {
        return cost>a.cost;
    }
};

vector<NodeCost>v[200010];
priority_queue<NodeCost>q;

void prim(int nod)
{
    long long curent, vecin, costvecin, cost,i;
    for(i=1; i<=n; i++)
        d[i]=max_value;
    d[nod]=0;
    t[nod]=0;
    q.push({nod,0});
    while(!q.empty())
    {
        curent=q.top().nod;
        cost=q.top().cost;
        q.pop();
        viz[curent]=1;
        for(auto it:v[curent])
        {
            vecin=it.nod;
            costvecin=it.cost;
            if(viz[vecin]==0&&d[vecin]>costvecin)
            {
                d[vecin]=costvecin;
                t[vecin]=curent;
                q.push({vecin,costvecin});
            }
        }
    }
}
void afis()
{
    long long s=0;
    for(int i=2; i<=n; i++)
        s+=d[i];
    cout<<s<<'\n';
    cout<<n-1<<'\n';
    for(int i=2; i<=n; i++)
        cout<<i<<' '<<t[i]<<'\n';
}
int main()
{
    cin>>n>>m;
    for(i=1; i<=m; i++)
    {
        cin>>x>>y>>c;
        v[x].push_back({y,c});
        v[y].push_back({x,c});
    }
    prim(1);
    afis();
    return 0;
}