Cod sursa(job #2216796)

Utilizator Horia14Horia Banciu Horia14 Data 27 iunie 2018 23:11:53
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include<cstdio>
#include<algorithm>
#define MAX_N 200000
#define MAX_M 400000
using namespace std;

struct edge {
    int x, y, c;
};

edge v[MAX_M];
vector<pair<int,int> >apm;
int p[MAX_N+1], h[MAX_N+1], n, m, minCost, apmSize;

inline bool cmp(edge a, edge b) {
    return a.c < b.c;
}

void readGraph() {
    FILE* fin = fopen("apm.in","r");
    fscanf(fin,"%d%d",&n,&m);
    for(int i = 0; i < m; i++)
        fscanf(fin,"%d%d%d",&v[i].x,&v[i].y,&v[i].c);
    fclose(fin);
}

void Init(int n) {
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        h[i] = 1;
    }
}

inline int Find(int x) {
    int r, aux;
    r = x;
    while(p[r] != r)
        r = p[r];
    while(p[x] != r) {
        aux = p[x];
        p[x] = r;
        x = aux;
    }
    return r;
}

void Kruskal() {
    int i, rootx, rooty;
    Init(n);
    sort(v,v+m,cmp);
    for(i = 0; apmSize < n - 1; i++) {
        rootx = Find(v[i].x);
        rooty = Find(v[i].y);
        if(rootx != rooty) {
            if(h[rootx] < h[rooty])
                p[rootx] = rooty;
            else if(h[rootx] > h[rooty])
                p[rooty] = rootx;
            else {
                p[rootx] = rooty;
                h[rooty]++;
            }
            apm.push_back(make_pair(v[i].x,v[i].y));
            apmSize++;
            minCost += v[i].c;
        }
    }
}

void printAPM() {
    vector<pair<int,int> >::iterator it;
    FILE* fout = fopen("apm.out","w");
    fprintf(fout,"%d\n%d\n",minCost,apmSize);
    for(it = apm.begin(); it != apm.end(); it++)
        fprintf(fout,"%d %d\n",(*it).first,(*it).second);
    fclose(fout);
}

int main() {
    readGraph();
    Kruskal();
    printAPM();
    return 0;
}