hdu 畅通工程 [Kruskal/Prime]

在这里插入图片描述

Kruskal +并查集+sort() 未AC

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<cstring>
#include<set>
using namespace std;
const int maxn = 110;

struct edge
{
	int u, v;
	int cost;
}E[maxn];

bool cmp(edge a, edge b)
{
	return a.cost < b.cost;
}

int father[maxn];

int findfather(int x)
{
	int a = x;
	while (x != father[x])
	{
		x = father[x];
	}
	while (a != father[a])
	{
		int z = a;
		a = father[a];
		father[z] = x;
	}
	return x;
}

void kruskal(int n, int m)
{
	int ans = 0, num_edge = 0;
	for (int i = 1; i <= m; i++)
	{
		father[i] = i;
	}
	sort(E, E + m, cmp);
	for (int i = 0; i < n; i++)
	{
		int fau = findfather(E[i].u);
		int fav = findfather(E[i].v);
		if (fau != fav)
		{
			father[fau] = fav;
			ans += E[i].cost;
			num_edge++;
			if (num_edge == n - 1) break;
		}
	}
	if (num_edge != n - 1) cout << "?" << endl;
	else cout << ans << endl;
}

int main()
{
	int n, m;
	while (cin >> n >> m , n)
	{
		for (int i = 0; i < n; i++)
		{
			cin >> E[i].u >> E[i].v >> E[i].cost;
		}
		kruskal(n, m);
	}
}

Prime AC 邻接表

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<cstring>
#include<set>
using namespace std;
const int maxn = 110;
const int inf = 1000000001;
struct node
{
	int v, cost;
	node() {}
	node(int _v, int _cost) :v(_v), cost(_cost){}
};
int n,m;
vector<node>adj[maxn];
bool vis[maxn];
int d[maxn];

int prime(int st)
{
	fill(d, d + maxn, inf);
	memset(vis, false, sizeof(vis));
	d[st] = 0;
	int ans = 0;
	for (int i = 0; i < m; i++)
	{
		int u = -1, min = inf;
		for (int j = 1; j <= m; j++)
		{
			if (vis[j] == false && d[j] < min)
			{
				u = j;
				min = d[j];
			}
		}
		if (u == -1) return -1;
		vis[u] = true;
		ans += d[u];
		for (int j = 0; j <adj[u].size(); j++)
		{
			int v = adj[u][j].v;
			if (vis[v] == false && adj[u][j].cost < d[v])
			{
				d[v] = adj[u][j].cost;
			}
		}
	}
	return ans;
}
int main()
{
	int u, v, cost;
	while (cin >> n >> m, n)
	{
		for (int i = 1; i <= m; i++) adj[i].clear();
		for (int i = 1; i <= n; i++)
		{
			cin >> u >> v >> cost;
			adj[u].push_back(node(v, cost));
			adj[v].push_back(node(u, cost));
		}
		int a = prime(1);
		if (a == -1) cout << "?" << endl;
		else cout << a << endl;
	}
}


posted @ 2020-08-03 23:16  _Hsiung  阅读(56)  评论(0编辑  收藏  举报