Cod sursa(job #2806547)

Utilizator AndreeaGeamanuAndreea AndreeaGeamanu Data 22 noiembrie 2021 19:08:11
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>

#define nmax 200010

using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");

vector <pair<int,int>> la[nmax];
int viz[nmax]={0};
priority_queue <pair<int,int>> pq;
vector <pair<int,int>> apm;


int main()
{   int n,m,x,y,c,s=0,nrmuchii=0;
    f>>n>>m;

    // Se introduc muchiile in liste de adiacenta
    for(int i=1; i<=m; i++){
        f>>x>>y>>c;
        la[x].push_back(make_pair(y,c));
        la[y].push_back(make_pair(x,c));
    }

    int v=1;
    viz[1]=1;

     struct muchie {
        int x,y,c;
        muchie(int x, int y, int c): x(x), y(y), c(c) {}
    };
    struct CompareC {
    bool operator()(muchie const& m1, muchie const& m2)
    {
        return m1.c > m2.c;
    }
    };
    priority_queue<muchie, vector<muchie>, CompareC> pq;

    for(int j=0; j<la[v].size(); j++){
        pq.push(muchie(v,la[v][j].first, la[v][j].second));
    }

    while(!pq.empty()){
        muchie top = pq.top();
        pq.pop();
        if(viz[top.y]==0){
            viz[top.y]=1;
            s=s+ top.c;
            nrmuchii++;
            apm.push_back(make_pair(top.x,top.y));

            for(int k=0; k<la[top.y].size(); k++){
                pq.push(muchie(top.y,la[top.y][k].first, la[top.y][k].second));
            }
        }
    }

    g<<s<<"\n"<<nrmuchii<<"\n";

    for(int l=0; l<apm.size(); l++){
        g<<apm[l].first<<" "<<apm[l].second<<"\n";
    }

    f.close();
    g.close();
    return 0;
}