Cod sursă (job #757077)

Utilizator avatar qpRares Bulgaru Rares qpRares IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 2,71 kb
Rundă Arhiva de probleme Status evaluat
Dată 22 ian. 2024 20:04:14 Scor 40
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(0), cin.tie(0), fin.tie(0);
using namespace std;
ofstream fout("zapada.out");

class edge
{
public:
    int x, y, cost;

    edge(int x, int y, int cost)
    {
        this->x = x;
        this->y = y;
        this->cost = cost;
    }

    bool operator<(const edge& a) const
    {
        return this->cost < a.cost;
    }
};
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;
	}
};
vector<int> t, Rank;

int Find(int i)
{
    if (t[i] == i)
        return i;
    return t[i] = Find(t[i]);
}

void Union(int x, int y)
{
    int x_root = Find(x);
    int y_root = Find(y);

    if (Rank[x_root] < Rank[y_root])
        t[x_root] = y_root;
    else if (Rank[x_root] > Rank[y_root])
        t[y_root] = x_root;
    else
    {
        t[x_root] = y_root;
        Rank[y_root]++;
    }
}

int kruskal(vector<edge>& edges, int n)
{
    sort(edges.begin(), edges.end());

    t.resize(n + 1);
    Rank.resize(n + 1, 0);

    for (int i = 1; i <= n; ++i)
        t[i] = i;

    int costMin = 0;

    for (auto& e : edges)
    {
        int x = e.x;
        int y = e.y;
        int cost = e.cost;

        if (Find(x) != Find(y))
        {
            costMin += cost;
            Union(x, y);
        }
    }

    return costMin;
}

int main()
{
    InParser fin("zapada.in");
    int n, m, k;
    fin >> n >> m >> k;

    vector<edge> edges;

    for (int i = 0; i < m; ++i)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges.emplace_back(x, y, cost);
    }

    int c0 = kruskal(edges, n);
    fout << c0 << '\n';

    for (int i = 0; i < k; ++i)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges.emplace_back(x, y, cost);
        int ck = kruskal(edges, n);
        fout << ck << '\n';
    }
    return 0;
}