hdu1857 畅通工程再续

用的堆优化的prim算法写的,之前把prim与dijkstra弄混了,prim是不用更新边的


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
const int INF = 1 << 30;
const int NIL = -1;
const int MAXN = 105;
int vis[MAXN];
double d[MAXN];
int head[20005];
int n;
int cnt;
struct Edge {
	int to, next;
	double w;
	Edge() {}
	Edge(int _to, double _w) :to(_to), w(_w) {}
	friend bool operator<(const Edge& a, const Edge& b)
	{
		return a.w > b.w;
	}
} edge[20005];

struct Coor {
	int x, y;
} coor[MAXN];


void add(int u, int v, double w)
{
	edge[cnt].to = v;
	edge[cnt].w = w;
	edge[cnt].next = head[u];
	head[u] = cnt++;
}

void prim(int n)
{
	priority_queue<Edge> q;
	for (int i = 0; i < n; ++i)
		vis[i] = false;
	double ans = 0.0;
	vis[0] = true;
	for (int i = head[0]; i != NIL; i = edge[i].next)
		q.push(edge[i]);
	Edge t;
	int u, v;
	double w;
	int count = 0;
	while (!q.empty() && count < n - 1)
	{
		t = q.top();
		q.pop();
		if (vis[t.to])
			continue;
		vis[t.to] = true;
		ans += t.w;
		++count;
		u = t.to;
		for (int i = head[u]; i != NIL; i = edge[i].next)
		{
			v = edge[i].to;
			if (!vis[v])
				q.push(edge[i]);
		}
	}
	if (count == n - 1)
		printf("%.1lf\n", ans * 100);
	else
		puts("oh!");

}


int main(void)
{
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout); 
	/*cin.tie(0);
	ios::sync_with_stdio(false);*/
	
	int T, c;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d", &c);
		for (int i = 0; i < c; ++i)
			scanf("%d%d", &coor[i].x, &coor[i].y);
		cnt = 0;
		memset(head, -1, 2 * sizeof(int) * c * c);
		for (int i = 0; i < c - 1; ++i)
			for (int j = i + 1; j < c; ++j)
			{
				int dist = (coor[j].x - coor[i].x) * (coor[j].x - coor[i].x) + (coor[j].y - coor[i].y) * (coor[j].y - coor[i].y);
				if (100 <= dist && dist <= 1000000)
				{
					double s = sqrt(dist);
					add(i, j, s);
					add(j, i, s);
				}
			}
		prim(c);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值