Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <numeric>
- #define DUMMY 0
- #define INF 1e9 // use this to represent the infinity
- using namespace std;
- // put your Disjoint Set here
- class DisjointSet {
- public:
- std::vector<int> ppt;
- DisjointSet(int size) {
- size++;
- ppt.resize(size);
- for (int i = 0; i < size; i++) {
- makeSet(i);
- }
- }
- void makeSet(int i) {
- ppt[i] = i;
- }
- int findSet(int i) {//path compression
- if (ppt[i]!= i) {
- ppt[i]= findSet(ppt[i]);
- }
- return ppt[i];
- }
- void unionSet(int i, int j) {
- int iParentIndex = findSet(i);
- int jParentIndex = findSet(j);
- ppt[jParentIndex] = iParentIndex;
- }
- bool isCycle(int i, int j) {
- if (findSet(i) == findSet(j)) return true;
- return false;
- }
- };
- class Graph {
- private:
- struct Edge {
- int u; int v; int w;
- Edge(int u, int v, int w) : u(u), v(v), w(w) { }
- bool operator < (const Edge& edge) const { return this->w < edge.w; }
- };
- vector<Edge> edges; //edge list used for Kruskal's algorithm
- int n; //number of edges
- public:
- Graph(int n) : n(n) {
- edges = vector<Edge>();
- }
- void insert_edge(int u, int v, int w) {
- edges.push_back(Edge(u, v, w));
- }
- vector<int> kruskal() {
- DisjointSet set(n);
- vector<int> kruskal_sequence(1, DUMMY); // store the weight of an edge
- // fill in here
- std::sort(edges.begin(), edges.end());
- // - you can sequentially iterate each edge as follows:
- // - for(Edge edge : edges)
- for (Edge edge : edges) {
- if (set.isCycle(edge.u, edge.v)) continue;
- else {
- set.unionSet(edge.u, edge.v);
- kruskal_sequence.push_back(edge.w);
- }
- }
- // - push back the weight of an edge selected by Kruskal into kruskal_sequence
- // (use kruskal_sequence.push_back(int weight))
- return kruskal_sequence;
- }
- };
- int main() {
- ios::sync_with_stdio(false);
- cin.tie(NULL);
- cout.tie(NULL);
- int n; // # of nodes
- int m; // # of edges
- int i; // index of a sequence to be printed
- cin >> n >> m >> i;
- Graph graph(n);
- for (int j = 0; j < m; j++) {
- int s, t, w;
- cin >> s >> t >> w;
- if (s > t) swap(s, t);
- graph.insert_edge(s, t, w);
- }
- vector<int> kruskal_sequence = graph.kruskal();
- // sum all entries of kruskal_sequence
- long long cost = std::accumulate(kruskal_sequence.begin(), kruskal_sequence.end(), 0);
- cout << cost << endl;
- cout << kruskal_sequence[i] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment