Cod sursa(job #2203142)

Utilizator vlcmodanModan Valentin vlcmodan Data 11 mai 2018 10:33:34
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

int n, m;
int x, y, length;

vector<bool> visited;
typedef struct Node {
	int source;
	int dest;
	int length;
}Node;
vector<vector<Node>> vec;
vector<Node> result;

struct compfunct {
	bool operator()(Node &a, Node &b) {
		return a.length > b.length;
	}
};
void kruskal(int start)
{
	priority_queue<Node, vector<Node>, compfunct> q;
	for (int i = 0; i < vec[start].size(); i++)
		q.push(vec[start][i]);
	visited[start] = true;

	while (!q.empty()) {
		Node n = q.top(); q.pop();

		if (!visited[n.dest]) {
			result.push_back(n);
			visited[n.dest] = true;

			for (int i = 0; i < vec[n.dest].size(); i++) {
				q.push(vec[n.dest][i]);
			}
		}
	}


}



void citire()
{
	scanf("%d %d", &n, &m);
	vec.resize(n + 1);
	visited.resize(n + 1);

	for (int i = 1; i <= m; i++) {
		scanf("%d %d %d", &x, &y, &length);
		Node a,b;
		a.source = x;
		a.dest = y;
		a.length = length;

		b = a;
		swap(b.source, b.dest);

		vec[x].push_back(a);
		vec[y].push_back(b);
	}
}

void afisare() {
	for (int i = 0; i < vec.size(); i++) {
		for (int j = 0; j < vec[i].size(); j++)
		{
			printf("%d %d %d\n", vec[i][j].source, vec[i][j].dest, vec[i][j].length);
		}
	}


}

int suma(vector<Node> &x) {
	int len = 0;
	for (int i = 0; i < x.size(); i++) {
		len += x[i].length;
	}
	return len;
}

void rezultat() {
	printf("%d\n", suma(result));
	printf("%d\n", result.size());
	for (int i = 0; i < result.size(); i++) {
		printf("%d %d\n", result[i].source, result[i].dest, result[i].length);
	}
}
int main()
{
	freopen("apm.in", "r", stdin);
	freopen("apm.out", "w", stdout);

	citire();
	//afisare();
	kruskal(1);

	rezultat();

	return 0;
}