Cod sursa(job #3242341)

Utilizator CondoracheAlexandruCondorache Alexandru CondoracheAlexandru Data 11 septembrie 2024 14:27:25
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
#define ll long long
const int INF = 1000000000;
using namespace std;

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


void prim(const vector<vector<pair<int, int>>>& adj) {
    int n = adj.size();
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
    vector<vector<pair<int, int>>> msp(n, vector<pair<int, int>>());
    vector<int> parent(n, -1);
    vector<int> vis(n, 0);
    q.push({0, 0});
    int cost = 0, size = 0;
    while (!q.empty()) {
        int c = q.top().first;
        int u = q.top().second;
        q.pop();
        if (vis[u]) {
            continue;
        }
        vis[u] = 1;
        cost += c;
        for (auto v : adj[u]) {
            if (!vis[v.second]) {
                q.push({v.first, v.second});
                parent[v.second] = u;
                size++;
            }
        }
    }
    fout << cost << endl;
    size = 0;
    //fout << size << endl;
    for (int i = 0; i < n; i++) {
        if (parent[i] != -1) {
            size++;
        }
    }
    fout << size << endl;
    for (int i = 0; i < n; i++) {
        if (parent[i] != -1) {
            fout << parent[i] + 1 << " " << i + 1 << endl;
        }
    }
}

void solve() {
    int n, m;
    fin >> n >> m;
    vector<vector<pair<int, int>>> adj(n, vector<pair<int, int>>());
    while (m--) {
        int x, y, c;
        fin >> x >> y >> c;
        x--;
        y--;
        adj[x].push_back({c, y});
        adj[y].push_back({c, x});
    }
    prim(adj);
}

int main() {
    int t = 1;
    // fin >> t;
    while (t--) {
        solve();
    }
    return 0;
}