BLINNET - Bytelandian Blingors Network - SPOJ Solution C++

  Problem Link : BLINNET  


👉 Hint : edit please

 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;
 
struct node
{
	int a,b,wt;
};
 
typedef struct node NODE;
 
int par[10001];
int size[10001];
 
vector<NODE>v;
 
bool comp(NODE a,NODE b)
{
	return a.wt<=b.wt;
}
 
int find(int a)
{
	if(par[a]==a)
		return a;
	return par[a]=find(par[a]);
}
 
bool uni(int a,int b)
{
	int p1=find(a);
	int p2=find(b);
	if(p1==p2)
		return false;
	if(size[p1]>size[p2])
	{
		par[p2]=p1;
		size[p1]+=size[p2];
	}
	else
	{
		par[p1]=p2;
		size[p2]+=size[p1];
	}
//	par[p2]=p1;
	return true;
 
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	int t;
	long long int ans;
	cin>>t;
	while(t--)
	{
		ans=0;
		v.clear();
		int n,x,w;
		cin>>n;
		string s;
		NODE edge;
		for(int i=1;i<=n;i++)
		{
			par[i]=i;
			size[i]=1;
		}
		for(int i=1;i<=n;i++)
		{
			cin>>s;
			int k;
			cin>>k;
			for(int j=1;j<=k;j++)
			{
				cin>>x>>w;
				if(x<i)
				    continue;
				edge.a=i;
				edge.b=x;
				edge.wt=w;
				v.push_back(edge);
 
			}
		}
		sort(v.begin(),v.end(),comp);
		int st,end,k=0;
		for(int i=0;i<v.size();i++)
		{
		    if(k==n-1)
		        break;
			st=v[i].a;
			end=v[i].b;
			w=v[i].wt;
			if(uni(st,end))
			{
				ans+=w;
				k++;
			}
		}
		cout<<ans<<endl;
	}
}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!