hdu1233 还是畅通工程 基础最小生成树

 //克鲁斯卡尔
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = ;
struct node
{
int begin, end, len;
}cun[maxn];
int n, fa[maxn], ans, m; bool cmp(node a, node b)
{
return a.len<b.len; //按长度有小到大排序
} void init()
{
for (int i = ; i <= n; i++)
{
fa[i] = i;
}
} int find(int x)
{
if (x == fa[x])
return fa[x];
else
return fa[x] = find(fa[x]);
} void join(int a, int b)
{
a = find(a);
b = find(b);
if (a != b)
fa[b] = a;
} int kruskal()
{
sort(cun, cun + m, cmp);
init(); //初始化并查集
ans = ;
for (int i = ; i<m; i++)
{
if (find(cun[i].begin) != find(cun[i].end)) //一条边的两个端点不在同一个集合,则选他,并合并
{
join(cun[i].begin, cun[i].end);
ans += cun[i].len;
}
}
return ans;
} int main()
{
while (cin >> n)
{
if (n == ) break;
m = n*(n - ) / ;
for (int i = ; i<m; i++)
cin >> cun[i].begin >> cun[i].end >> cun[i].len;
cout << kruskal() << endl;
}
return ;
}
 //prim
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std; #define INF 0x7fffffff
# define MAXN
typedef long long int LL; LL n, m;
LL cmpa[MAXN][MAXN], book[MAXN], dis[MAXN]; int main()
{
LL a, b, weight, ans, p, q, f1, f2, minn, mark;
while (scanf("%I64d", &n) && n)
{
//初始化 这题prime算法合适,边那摩多,都是完全图了
for (LL i = ; i<MAXN; i++)
{
dis[i] = INF;
for (LL j = ; j<MAXN; ++j)
cmpa[i][j] = INF;
} memset(book, , sizeof(book));
ans = ; for (LL i = ; i<n*(n - ) / ; ++i)
{
scanf("%I64d %I64d %I64d", &a, &b, &weight);
cmpa[a][b] = cmpa[b][a] = weight;
} //连通图
book[] = ;
dis[] = -; for (LL t = ; t<n; ++t)
{
for (LL i = ; i <= n; ++i)
{//更新dis中的值
for (LL j = ; j <= n; ++j)
{
if (book[j] && dis[i]>cmpa[i][j])
{ //j在树中
dis[i] = cmpa[i][j];
}
}
} //选点建树
minn = INF, mark = ;
for (LL i = ; i <= n; ++i)
{
if (book[i])
continue;
else
{
if (dis[i] < minn)
{
minn = dis[i];
mark = i;
}
}
} if (minn != INF)
{
ans += minn;
book[mark] = ;
dis[mark] = -;
} }
cout << ans << endl; }
return ;
}
上一篇:最小生成树: HDU1233还是畅通工程


下一篇:(最小生成树 )还是畅通工程 -- HDU--1233