Cod sursa(job #2594942)

Utilizator DawlauAndrei Blahovici Dawlau Data 6 aprilie 2020 20:00:29
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

class InParser {

private:

	static const int buffSZ = (1 << 15);
	ifstream File;
	int buffPos;
	char buff[buffSZ];

	void _advance() {

		if (++buffPos == buffSZ) {

			File.read(buff, buffSZ);
			buffPos = 0;
		}
	}

public:

	InParser(const char *FileName) {

		buffPos = buffSZ - 1;
		File.open(FileName);
	}

	InParser& operator >>(int &no) {

		while (!isdigit(buff[buffPos]))
			_advance();
		no = 0;
		while (isdigit(buff[buffPos])) {

			no = no * 10 + buff[buffPos] - '0';
			_advance();
		}
		return *this;
	}
};

InParser fin("arhipelag.in");
ofstream fout("arhipelag.out");

const int VMAX = 1e5;

vector <int> player, ans, dad, lvl, sz, comp;
int V, E, K;

int Find(int node) {

	int root = node;
	for (; root != dad[root]; root = dad[root]);

	while (root != node) {

		int auxNode = node;
		node = dad[node];
		dad[auxNode] = root;
	}

	return root;
}

void Union(int node1, int node2) {

	if (lvl[node1] >= lvl[node2]) {

		dad[node2] = node1;
		sz[node1] += sz[node2];
	}
	else {

		dad[node1] = node2;
		sz[node2] += sz[node1];
	}

	if (lvl[node1] == lvl[node2])
		++lvl[node1];
}

void readData() {

	fin >> V >> E >> K;

	player.resize(K);
	ans.resize(K);
	dad.resize(1 + V);
	lvl.resize(1 + V, 1);
	sz.resize(1 + V, 1);
	comp.reserve(V);

	for (int node = 1; node <= V; ++node)
		dad[node] = node;

	for (; E; --E) {

		int from, to;
		fin >> from >> to;

		if (from > to)
			swap(from, to);

		int root1 = Find(from);
		int root2 = Find(to);

		if (root1 != root2)
			Union(root1, root2);
	}

	for (int &itm : player)
		fin >> itm;
}

void reset() {

	player.clear();
	ans.clear();
	dad.clear();
	lvl.clear();
	sz.clear();
	comp.clear();
}

int main() {

	int T;
	fin >> T;

	for (int t = 1; t <= T; ++t) {

		readData();

		for (int node = 1; node <= V; ++node)
			if (node == dad[node])
				comp.push_back(sz[node]);

		sort(comp.begin(), comp.end(), [](const int &a, const int &b) { return a > b; });

		for (int idx = 0, c = 0; c < comp.size(); ++idx, idx %= K, ++c)
			ans[player[idx] - 1] += comp[c];

		fout << "Case " << t << ": ";

		for (const int &itm : ans)
			fout << itm << ' ';
		fout << '\n';

		reset();
	}
}