Cod sursa(job #2353261)

Utilizator ilucianIlea Lucian ilucian Data 24 februarie 2019 09:30:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>
#include <algorithm>
#include <stdio.h>
#include <ctype.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;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long 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;
	}
};

InParser fi("apm.in");
ofstream fo("apm.out");

struct muchie { int v1,v2,cost;};

int n,m;
muchie E[400002];

int P[200002];
int NR[200002];
int REZ[400002];

int cmp(muchie a, muchie b)
{
    return a.cost<b.cost;
}

int parinte(int v)
{
    int x;
    x=v;
    while (P[x]!=x)
        x=P[x];
    while (P[v]!=v)
    {
        int cv;
        cv=v;
        v=P[v];
        P[cv]=x;
    }
    return x;
}

int main()
{
    fi>>n>>m;
    for(int i=1;i<=m;i++)
        fi>>E[i].v1>>E[i].v2>>E[i].cost;
    sort(E+1,E+m+1,cmp);
    for (int i=1;i<=n;i++)
    {
        P[i]=i;
        NR[i]=1;
    }
    int s=0;
    int nr=0;
    for(int i=1;i<=m;i++)
    {
        int p1=parinte(E[i].v1);
        int p2=parinte(E[i].v2);
        if (p1!=p2)
        {
            nr++;
            REZ[nr]=i;
            s=s+E[i].cost;
            /// unificare de arbori
            if (NR[p1]<=NR[p2])
            {
                NR[p2]+=NR[p1];
                P[p1]=p2;
            }
            else
            {
                NR[p1]+=NR[p2];
                P[p2]=p1;
            }
        }
    }
    fo<<s<<'\n';
    fo<<n-1<<'\n';
    for(int i=1;i<=nr;i++)
        fo<<E[REZ[i]].v1<<' '<<E[REZ[i]].v2<<'\n';
    fo.close();
    return 0;
}