Cod sursa(job #2127107)

Utilizator Horia14Horia Banciu Horia14 Data 10 februarie 2018 12:26:55
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include<cstdio>
#include<algorithm>
#define MAX_N 200000
#define MAX_M 400000
using namespace std;

struct edge {
    int x, y;
    short cost;
};

struct APM {
    int x, y;
};

edge v[MAX_M];
APM a[MAX_N];
int p[MAX_N + 1], h[MAX_N + 1], n, m, minCost, k;

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

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%hd",&v[i].x,&v[i].y,&v[i].cost);
    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 tmp, aux;
    aux = x;
    while(p[aux] != aux)
        aux = p[aux];
    while(p[x] != aux) {
        tmp = p[x];
        p[x] = aux;
        x = tmp;
    }
    return aux;
}

inline void Union(int x, int y, int i) {
    int rootx, rooty;
    rootx = Find(x);
    rooty = Find(y);
    if(rootx != rooty) {
        minCost += v[i].cost;
        a[k].x = x;
        a[k++].y = y;
        if(h[rootx] < h[rooty])
            p[rootx] = rooty;
        else if(h[rootx] > h[rooty])
            p[rooty] = rootx;
        else {
            p[rootx] = rooty;
            h[rooty]++;
        }
    }
}

void Kruskal() {
    Init(n);
    sort(v,v+m,cmp);
    for(int i = 0; k < n - 1; i++)
        Union(v[i].x,v[i].y,i);
}

void printAPM() {
    FILE *fout = fopen("apm.out","w");
    fprintf(fout,"%d\n%d\n",minCost,k);
    for(int i = 0; i < k; i++)
        fprintf(fout,"%d %d\n",a[i].x,a[i].y);
    fclose(fout);
}

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