本文主要是介绍HDU 1102(最小生成树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:给一个图,以及已知一些边已经存在,求除了给出的这些边,至少需要多长的边才能使所有结点相连接。
kruskal:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct edge
{
int u, v, w;
edge() {}
edge(int _u, int _v, int _w) : u(_u), v(_v), w(_w) {}
bool operator <(const edge& rhs) const
{
return w > rhs.w;
}
};
int map[101][101];
int set[101];
int find(int x)
{
return set[x] == -1 ? x : set[x] = find(set[x]);
}
int kruskal(int n)
{
priority_queue<edge> q;
int ans = 0, i, j;
for (i = 1; i <= n; ++i)
for (j = 1; j < i; ++j)
q.push(edge(i, j, map[i][j]));
while (!q.empty())
{
edge p = q.top(); q.pop();
int x = find(p.u), y = find(p.v);
if (x != y) set[x] = y, ans += p.w;
}
return ans;
}
int main()
{
int n, q, i, j;
while (scanf("%d", &n) != EOF)
{
memset(set, -1, sizeof set);
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
{
scanf("%d", &map[i][j]);
map[j][i] = map[i][j];
}
scanf("%d", &q);
while (q--)
{
scanf("%d%d", &i, &j);
map[i][j] = map[j][i] = 0;
}
printf("%d\n", kruskal(n));
}
}
prim:
#include <cstdio>
#include <cstring>
#include <queue>
#include <climits>
using namespace std;
struct edge
{
int u, v, w;
edge() {}
edge(int _u, int _v, int _w) : u(_u), v(_v), w(_w) {}
bool operator <(const edge& rhs) const
{
return w > rhs.w;
}
};
int map[101][101];
/*
int prim(int n)
{
int i;
bool visited[101];
int distance[101];
memset(visited, false, sizeof visited);
for (i = 1; i <= n; ++i) distance[i] = INT_MAX;
int v = 1, dist;
distance[v] = 0;
int sum = 0;
while (visited[v] == false)
{
visited[v] = true;
sum += distance[v];
for (i = 1; i <= n; ++i)
if (visited[i] == false && map[v][i] < distance[i])
distance[i] = map[v][i];
dist = INT_MAX;
for (i = 1; i <= n; ++i)
if (visited[i] == false && dist > distance[i])
{
dist = distance[i];
v = i;
}
}
return sum;
}
*/
int prim(int n)
{
bool visited[101];
memset(visited, false, sizeof visited);
visited[1] = true;
int i, sum = 0, j, flag, min;
for (i = 1; i < n; ++i)
{
min = INT_MAX;
for (j = 1; j <= n; ++j)
if (!visited[j] && map[1][j] < min)
{
min = map[1][j];
flag = j;
}
visited[flag] = true;
sum += map[1][flag];
for (j = 1; j <= n; ++j)
if (!visited[j] && map[1][j] > map[flag][j])
map[1][j] = map[flag][j];
}
return sum;
}
int main()
{
int n, q, i, j;
while (scanf("%d", &n) != EOF)
{
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
{
scanf("%d", &map[i][j]);
map[j][i] = map[i][j];
}
scanf("%d", &q);
while (q--)
{
scanf("%d%d", &i, &j);
map[i][j] = map[j][i] = 0;
}
printf("%d\n", prim(n));
}
}
这篇关于HDU 1102(最小生成树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!