Cod sursa(job #2189904)

Utilizator Horia14Horia Banciu Horia14 Data 29 martie 2018 12:32:54
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
// Kruskal neoptimizat
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cctype>
#define MAX_N 200000
#define MAX_M 400000
#define BUF_SIZE 1 << 18
using namespace std;

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

edge v[MAX_M];
vector<pair<int,int> >apm;
int p[MAX_N + 1], h[MAX_N + 1], n, m, minCost, apmSIZE, pos = BUF_SIZE;
char buf[BUF_SIZE];

char getChar(FILE* fin) {
    if(pos == BUF_SIZE) {
        fread(buf,1,BUF_SIZE,fin);
        pos = 0;
    }
    return buf[pos++];
}

int read(FILE* fin) {
    int res, semn;
    char ch;
    res = 0, semn = 1;
    do {
        ch = getChar(fin);
        if(ch == '-')
            semn = -semn;
    }while(!isdigit(ch));
    do {
        res = 10*res + ch - '0';
        ch = getChar(fin);
    }while(isdigit(ch));
    return res*semn;
}

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

void readGraph() {
    FILE* fin = fopen("apm.in","r");
    n = read(fin); m = read(fin);
    for(int i = 0; i < m; i++) {
        v[i].x = read(fin);
        v[i].y = read(fin);
        v[i].cost = read(fin);
    }
    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;
}

inline void Union(int x, int y, int i) {
    int rx, ry;
    rx = Find(x);
    ry = Find(y);
    if(rx != ry) {
        p[rx] = ry;
        apmSIZE++;
        minCost += v[i].cost;
        apm.push_back(make_pair(x,y));
        /*if(h[rx] < h[ry])
            p[rx] = ry;
        else if(h[rx] > h[ry])
            p[ry] = rx;
        else {
            p[rx] = ry;
            h[ry]++;
        }*/
    }
}

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

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