Cod sursa(job #3245570)

Utilizator AlexanderCernyCernaianu Alexandru AlexanderCerny Data 29 septembrie 2024 14:03:18
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

ifstream fin ("apm.in");
ofstream fout("apm.out");

struct vec
{
    int x,cost;
};
struct cmp
{
    bool operator()(vec a, vec b)
    {
        return a.cost>b.cost;
    }
};
vector<vec>g[200001];
priority_queue<vec,vector<vec>,cmp>heap;
int n,m,minim,vc,p;
int cost[200001];
bool viz[200001];
int tata[200001];
int x,y,c,sol;
int main()
{
    fin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        fin>>x>>y>>c;
        g[x].push_back({y,c});
        g[y].push_back({x,c});
    }
    for(int i=2;i<=n;i++)
        cost[i]=INT_MAX;
    heap.push({1,0});
    while(!heap.empty())
    {
        p=heap.top().x;
        int c=heap.top().cost;
        heap.pop();
        if(viz[p]==1)
            continue;
        viz[p]=1;
        sol+=c;
        for(int j=0;j<g[p].size();j++)
        {
            vc=g[p][j].x;
            int ct=g[p][j].cost;
            if(cost[vc]>ct && viz[vc]==0)
            {
                cost[vc]=ct;
                tata[vc]=p;
                heap.push({vc,ct});
            }
        }
    }
    fout<<sol<<'\n'<<n-1<<'\n';
    for(int i=2;i<=n;i++)
        fout<<i<<" "<<tata[i]<<'\n';
    return 0;
}