hdu 畅通工程再续(最小生成树---Kruscal)

https://blog.csdn.net/Wiking__acm/article/details/7831232 

#include<bits/stdc++.h>
using namespace std;
struct Node
{
	int posx, posy;
}node[1000];
struct Edg
{
	int u, v;
	double e;
	bool operator <(const Edg &p)const 
	{
		return e < p.e;
	}
}edg[1000];
double Dis(Node x, Node y)
{
	return sqrt((x.posx - y.posx)*(x.posx - y.posx) + (x.posy - y.posy)*(x.posy - y.posy));
}
int Father[1000];
int FindFather(int x) { return Father[x] < 0 ? x : FindFather(Father[x]); }
double ans = 0;
void Umerge(Edg x)
{
	int Fx = FindFather(x.u);
	int Fy = FindFather(x.v);
	if (Fx != Fy)
	{
		Father[Fy] += Father[Fx];
		Father[Fx] = Fy;
		ans += x.e;
	}
}
int main()
{
	int T; cin >> T;
	while (T--)
	{
		memset(Father, -1, sizeof(Father));
		memset(node, 0, sizeof(node));
		memset(edg, 0, sizeof(edg));
		int n; cin >> n;
		for (int i = 0; i < n; i++)
		{
			cin >> node[i].posx >> node[i].posy;
		}
		int cnt = 0;
		for (int i = 0; i < n; i++)
		{
			for (int j = i+1; j < n; j++)
			{
				double dis = Dis(node[i], node[j]);
				if (dis<=1000&&dis>=10)
				{
					edg[cnt].u = i;
					edg[cnt].v = j;
					edg[cnt].e = dis;
					cnt++;
				}
			}
		}
		sort(edg, edg + cnt);
		for (int i=0;i<cnt;++i)
		{
			cout << edg[i].u << " " << edg[i].v << " " << edg[i].e<<"\n";
		}
		
		for (int i = 0; i < cnt; ++i) Umerge(edg[i]);
	
		int num=0;
		for (int i = 0; i < n; i++)  if (Father[i] < 0)num++;

		num == 1 ? printf("%.1lf\n", ans * 100): printf("oh!\n");
	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_31741481/article/details/83244959
今日推荐