Cod sursa(job #2314486)

Utilizator Horia14Horia Banciu Horia14 Data 8 ianuarie 2019 16:27:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include<cstdio>
#include<vector>
#define MAX_N 200000
#define MAX_M 400000
using namespace std;

struct edge {
    int x, y, cost;
} v[MAX_M];

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

void quickSort(int Begin, int End) {
    int b = Begin, e = End, pivot = v[(b+e)>>1].cost;
    edge aux;
    while(b <= e) {
        while(v[b].cost < pivot)
            b++;
        while(v[e].cost > pivot)
            e--;
        if(b <= e) {
            aux = v[b];
            v[b] = v[e];
            v[e] = aux;
            b++;
            e--;
        }
    }
    if(Begin < e)
        quickSort(Begin,e);
    if(b < End)
        quickSort(b,End);
}

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;
}

inline void Union(int x, int y, int c) {
    int rootx, rooty;
    rootx = Find(x);
    rooty = Find(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(x,y));
        apmSize++;
        minCost += c;
    }
}

void Kruskal() {
    int i = 0;
    quickSort(0,m-1);
    init(n);
    while(apmSize < n - 1) {
        Union(v[i].x,v[i].y,v[i].cost);
        i++;
    }
}

void printAPM() {
    FILE* fout = fopen("apm.out","w");
    fprintf(fout,"%d\n%d\n",minCost,apmSize);
    for(auto i : apm)
        fprintf(fout,"%d %d\n",i.first,i.second);
    fclose(fout);
}

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

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