Cod sursa(job #2204292)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 15 mai 2018 12:44:35
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>

using namespace std;

class InParser {
private:
    FILE *fin;
    char *buff;
    int sp;

    char read_ch() {
        ++sp;
        if (sp == 4096) {
            sp = 0;
            fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }

public:
    InParser(const char* nume) {
        fin = fopen(nume, "r");
        buff = new char[4096]();
        sp = 4095;
    }

    InParser& operator >> (int &n) {
        char c;
        while (!isdigit(c = read_ch()) && c != '-');
        int sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }
};



struct edge{
    int x, y, c;
    bool operator<(const edge &obj)const{
        return c >= obj.c;
    }
};

int n, m;
bool ok[200005];
priority_queue<edge> q;
vector<edge> v[200005], sol;

edge make_edge(int x, int y, int c)
{
    edge aux;
    aux.x = x;
    aux.y = y;
    aux.c = c;
    return aux;
}

int main()
{
    InParser fin ("apm.in");
    ofstream fout ("apm.out");
    fin >> n >> m;
    for (int i = 1; i <= m; ++i){
        int x, y, z;
        fin >> x >> y >> z;
        v[x].push_back(make_edge(x, y, z));
        v[y].push_back(make_edge(x, y, z));
    }
    for (vector<edge>::iterator it = v[1].begin(); it != v[1].end(); ++it)
        q.push(*it);
    int apm = 0;
    for (int t = 1; t < n; ++t){
        while(ok[q.top().x] && ok[q.top().y])
            q.pop();
        int x = q.top().x, y = q.top().y, c = q.top().c;
        sol.push_back(q.top());
        apm += c;
        q.pop();
        if(!ok[x]){
            for (vector<edge>::iterator it = v[x].begin(); it != v[x].end(); ++it)
                if(!((it->x == x && it->y == y) || (it->y == x && it->x == y)))
                    q.push(*it);
        }
        if(!ok[y]){
            for (vector<edge>::iterator it = v[y].begin(); it != v[y].end(); ++it)
                if(!((it->x == x && it->y == y) || (it->y == x && it->x == y)))
                    q.push(*it);
        }
        ok[x] = ok[y] = 1;
    }
    fout << apm << '\n' << n-1 << '\n';
    for (int i = 0; i < n-1; ++i)
        fout << sol[i].x << ' ' << sol[i].y << '\n';
    return 0;
}