Pagini recente » Cod sursa (job #891819) | Cod sursa (job #2296354) | Cod sursa (job #43582) | Cod sursa (job #1857308) | Cod sursa (job #3224454)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct muchie
{
int node1, node2, cost;
bool operator<(const muchie& temp) const
{
return cost < temp.cost;
}
};
struct ceva
{
int node, cost;
};
int n, m, q;
vector<int> parent;
vector<int> depth;
int root(int x)
{
int repX;
for(repX = x; repX != parent[repX]; repX = parent[repX]);
return repX;
}
void unire(int x, int y)
{
int repX = root(x);
int repY = root(y);
if(repX == repY) return;
if(depth[repX] > depth[repY]) parent[repY] = repX;
else if(depth[repY] > depth[repX]) parent[repX] = repY;
else
{
depth[repX]++;
parent[repY] = repX;
}
}
int main()
{
cin>>n>>m>>q;
vector<muchie> muc;
muc.resize(m+1);
for(int i = 1;i<=m;i++)
{
int x, y, cost;
cin>>x>>y>>cost;
muc[i] = {x, y, cost};
}
sort(muc.begin() + 1, muc.begin() + m + 1);
parent.resize(m+1), depth.resize(m+1);
for(int i = 1;i<=m;i++)
{
parent[i] = i;
depth[i] = 1;
}
vector<vector<int>> adj;
adj.resize(n+1);
for(int i = 1;i<=m;i++)
{
int node1 = muc[i].node1;
int node2 = muc[i].node2;
int cost = muc[i].cost;
if(root(node1) != root(node2))
{
adj[node1].push_back(node2);
adj[node2].push_back(node1);
unire(node1, node2);
}
}
}